将铁-ajax数据绑定到模板

时间:2015-07-13 18:51:57

标签: ajax data-binding polymer

我有一个Polymer(1.0)应用程序从AJAX加载books列表:

book-service/book-service.html

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

<dom-module id="book-service">
    <style>

    </style>

    <template>
        <iron-ajax
          auto
          url="https://example.com/books.json"
          handle-as="json"
          on-response="booksLoaded"></iron-ajax>
    </template>

    <script>
    Polymer({
        is: 'book-service',

        properties: {
            books: { type: Array }
        },

        created: function(){
            this.books = [];
        },

        booksLoaded: function(request){
            this.books = request.detail.response
        }
    });
    </script>
</dom-module>

components/book-list.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../book-service/book-service.html">

<dom-module id="book-list">
    <style>

    </style>

    <template>
        <book-service id="service" books="{{books}}"></book-service>

        <div>
            <div>Books:</div>
            <ul>
            <template is="dom-repeat" items="{{books}}">
                <li>{{item.title}}</li>
            </template>
            </ul>
        </div>
    </template>

    <script>
    Polymer({is: 'book-list'});
    </script>
</dom-module>

虽然我可以确认AJAX请求正在接收JSON,但DOM中没有任何更改。然后我注意到Polymer 1数据绑定指南中的注释需要使用Polymer方法,所以我尝试了显示的内容,响应处理程序变为:

booksLoaded: function(request){
    this.push('books', request.detail.response);
}

但现在我收到了错误! Uncaught TypeError: Cannot read property 'concat' of undefined

如何将AJAX响应实际绑定到模板?

1 个答案:

答案 0 :(得分:6)

使用notify属性传播属性更改以进行绑定。

properties: {
    books: { type: Array, notify: true }
},

此外,您可以使用以下功能缩减booksLoadedcreated个功能:

<dom-module id="book-service">
    <template>
        <iron-ajax
          auto
          url="https://example.com/books.json"
          handle-as="json"
          last-response="{{books}}"></iron-ajax>
    </template>

    <script>
    Polymer({
        is: 'book-service',
        properties: {
            books: {
              type: Array,
              notify: true,
              value: function(){return []}
            }
        }
    });
    </script>
</dom-module>