confused about the polymer published attributes

久未见 提交于 2019-12-20 07:24:01

问题


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:

  1. make response a published attribute by setting attributes="response ..."
  2. 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.


回答1:


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



来源:https://stackoverflow.com/questions/25050120/confused-about-the-polymer-published-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!