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?
Three main problems:
core-ajax must go inside the template, so it's part of each instance's DOM (this is why ajax was undefined).auto attribute on the core-ajax (otherwise, you must call the go() method on the core-ajax to send the request).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:
core-ajax, we don't need to reference it anymore.polymer.html import, core-ajax already imports it. 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With