我开始使用 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
永远不会被调用。可能出了什么问题?