2
我開始使用Backbone.js,但似乎無法獲得最簡單的概念驗證工作。我有以下代碼:'add'事件在取出時似乎沒有觸發
$(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
永遠不會被調用。可能會出現什麼問題?
除非你通過{添加:真正}的選項來獲取,在這種情況下,將增加的項目(和火災事件的「添加」)到集合,而不是將其復位的。 – jimr