获取时,“添加”事件似乎不会触发

时间:2012-05-04 19:52:53

标签: backbone.js

我开始使用Backbone.js,但似乎无法获得最简单的概念验证工作。我有以下代码:

$(function() {

    var Contact = Backbone.Model.extend({

        url: 'contacts.txt'

    });

    var ContactList = Backbone.Collection.extend({

        model: Contact,
        url: 'contacts.txt'

    });

    var Contacts = new ContactList();

    var ContactView = Backbone.View.extend({

        tagName: 'li',

        template: _.template($('#contact-template').html()),

        initialize: function() {
            _.bindAll(this);
        },

        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }

    });

    var AppView = Backbone.View.extend({

        el: '#contacts',

        initialize: function() {
            Contacts.bind('add', this.addOne, this);
            Contacts.fetch();
        },

        addOne: function(Contact) {
            var view = new ContactView({model: Contact});
            this.$el.append(view.render().el);
        }

    });

    var app = new AppView();

});

文件contacts.txt包含一个简单的JSON结构,根据Chrome可以正常加载:

[{"from_acct_id": 5, "ct": 0, "from_display_nm": "Name 1", "to_acct_id": 1},
 {"from_acct_id": 3, "ct": 1, "from_display_nm": "Name 2", "to_acct_id": 1},
 {"from_acct_id": 2, "ct": 0, "from_display_nm": "Name 3", "to_acct_id": 1},
 {"from_acct_id": 4, "ct": 1, "from_display_nm": "Name 4", "to_acct_id": 1}]

无论出于何种原因,永远不会调用绑定到addOne()add事件的AppView函数。可能出现什么问题?

1 个答案:

答案 0 :(得分:1)

Backbone集合的提取调用将触发重置事件。绑定重置。

http://documentcloud.github.com/backbone/#Collection-fetch