confused about the polymer published attributes
-
21-12-2019 - |
Question
I have dig to the ajax-core element of polymer, code like the follows works fine:
<core-ajax url="./ajax-test.txt" auto response="{{resp}}"></core-ajax>
<textarea value="{{resp}}"></textarea>
I can get the value from {{resp}}
in this case. I have dig into the core-ajax source code and find out how it has been done:
- make
response
a published attribute by settingattributes="response ..."
- pass the ajax response to
this.response
then I tried to build my own ajax component but it didn't worked, my ajax component code is:
Polymer('louis-ajax', {
url: '',
response: null,
ready: function() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
this.response = xmlhttp.responseText;
}
}.bind(this);
xmlhttp.open("GET",this.url,true);
xmlhttp.send();
}
});
and my app code is this:
<louis-ajax url="http://polymer.snspay.cn/api/posts.json" response="{{response}}"></louis-ajax>
<span>We have got the ajax response as</span> : <input type='text' value="{{response}}" />
The result is the ajax request has been successfully done, but the value of input is "{{response}}", not the value of {{response}}, so I think there is something wrong about how I understanding the published attributes work, any helps? Thk.
Solution
I know you said you figured it out, but for others coming to this page looking for a fully-working solution and explanation, here it is.
If you want data binding without having to create a custom element, you must put your code into a template with the is
attribute set to auto-binding
:
<template is="auto-binding">
<core-ajax url="./ajax-test.txt" auto response="{{resp}}"></core-ajax>
<textarea value="{{resp}}"></textarea>
</template>
Without this, Polymer won't know it needs to hook up the bindings in your html, and things like {{resp}}
will be treated as text.
More detailed explanation can be found here: http://www.polymer-project.org/docs/polymer/databinding-advanced.html#autobinding