Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

polymer - loading core ajax inside an element

After checking core-ajax usage in the polymer website I decided to add ajax functionality using core-ajax inside my element/widget.

test-view.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/core-ajax/core-ajax.html">

<polymer-element name="test-view" attributes="url">
    <core-ajax id="elemAjax" url="{{url}}" handleAs="json"></core-ajax>
    <template>
        <div id="body"></div>
    </template>
    <script>
        Polymer('test-view', {
        ready: function() {
            var ajax = this.$.elemAjax; // this line
            ajax.addEventListener('core-response', function() {
                console.log(this.response);
            });
        }
    });
    </script>
</polymer-element>

Unfortunately, the "ajax" variable in my script returns "undefined". How can I load ajax inside an element using core-ajax?

Side Question: Is the "id" attribute inside a polymer element only accessible inside the polymer element?

like image 610
Gasim Avatar asked Jun 23 '14 06:06

Gasim


1 Answers

Three main problems:

  1. The core-ajax must go inside the template, so it's part of each instance's DOM (this is why ajax was undefined).
  2. You need the auto attribute on the core-ajax (otherwise, you must call the go() method on the core-ajax to send the request).
  3. Your event handler uses this but is not bound to the element scope. Suggest you use event delegation instead of addEventListener.

See the new example below. The other (less important) tweaks I made:

  1. Remove id from core-ajax, we don't need to reference it anymore.
  2. Remove the polymer.html import, core-ajax already imports it.
  3. Remove the test-view parameter to Polymer(), it's not necessary when defining an element inside an import.

Modified example:

<link rel="import" href="bower_components/core-ajax/core-ajax.html">

<polymer-element name="test-view" attributes="url">
<template>
    <core-ajax auto url="{{url}}" handleAs="json" on-core-response="{{ajaxResponse}}"></core-ajax>
    <div id="body"></div>
</template>
<script>
    Polymer({
        ajaxResponse: function(event, response) {
            console.log(response);
        }
    });
</script>
</polymer-element>

Even better is to avoid events altogether and data-bind directly to the response data. Example:

<link rel="import" href="bower_components/core-ajax/core-ajax.html">

<polymer-element name="test-view" attributes="url">
<template>
    <core-ajax auto url="{{url}}" handleAs="json" response="{{response}}"></core-ajax>
    <div id="body"></div>
</template>
<script>
    Polymer({
        responseChanged: function(oldValue) {
            console.log(this.response);
        }
    });
</script>
</polymer-element>
like image 181
Scott Miles Avatar answered Oct 03 '22 19:10

Scott Miles