Backbone.js迭代来自fetch()的JSON结果

时间:2012-07-03 05:43:11

标签: backbone.js

我对Backbone非常陌生,只想弄清楚事情的运作方式。如何迭代“获取的”结果?

(function($) {
    console.log('Formcontainer init.'); 

    var Field = Backbone.Model.extend({
        defaults: {
            id: "0",
            memberlist_id: "3",
            field_name: "sample-field-name",
        },
        initialize: function() {
            console.log('Field model init.');
        }
    });

    var FieldCollection = Backbone.Collection.extend({
        defaults: {
            model: Field
        },
        model: Field,
        url: 'http://localhost:8888/getstuff/3.json',
        initialize: function() {
            console.log('FieldCollection init.');
        }
    });

    var ListView = Backbone.View.extend({
        el: '#app-container',

        initialize: function() {
            _.bindAll(this,"render");
            console.log('ListView init.')
            this.counter = 0;

            this.collection = new FieldCollection();
            this.collection.fetch();
            //this.collection.bind('reset', function() { console.log('xxx')});
            //this.collection.fetch();

            this.render();
        },

        events: {
            'click #add': 'addItem'
        },

        render: function() {
            var self = this;
            console.log('Render called.');
        },

        addItem: function() {
            this.counter++;
            this.$("ul").append("<li>hello world" + this.counter + "</li>");
        }
    });

    var listView = new ListView();

})(jQuery);

我在Firebug控制台中得到了这个:

Formcontainer init.
ListView init.
FieldCollection init.
GET http://localhost:8888/getstuff/3.json 200 OK
Render called.
Field model init.
Field model init.
Field model init.
Field model init.
Field model init.

似乎调用了fetch() - 因为“Field model init”。在控制台中5次。但是如何输出呢?我想将这些项目附加在无序列表中。

谢谢!

1 个答案:

答案 0 :(得分:1)

重置事件绑定到呈现功能...

this.collection.bind('reset', this.render, this);

fetch 完成后会触发此操作,因此您可以创建列表...

render: function() {
    var self = this;
    console.log('Render called.');
    this.collection.each(function(i,item) {
        this.$el.append("<ul>" + item.get("field_name") + "</ul>");
    });
},