[英]backbone.js view events not firing
我有點主力軍,所以請多多包涵。
我正在嘗試使用骨干.js動態生成聯系人列表,並將onclick事件處理程序附加到每個列表,但無濟於事。 我的視圖呈現良好,但單擊事件未注冊。 這是我的代碼:
App.Views.Contact = Backbone.View.extend({
initialize: function() {
this.render();
},
events: {
'click': 'select',
},
select: function(event) {
console.log('contact selected');
},
render: function() {
$('#contacts').append(tmplContact(this.model.toJSON()));
}
});
更新:這是相應集合的代碼
App.Collections.Contact = Backbone.Collection.extend({
initialize: function() {
this.bind('reset', function() {
console.log('COLLECTION RESET');
});
},
model: App.Models.Contact,
comparator: function(model) {
return model.get('name');
}
});
更新2:集合的初始化和填充
App.Collections.roster = new App.Collections.Contact;
function getContacts() {
socketRequest('friends', function(data) {App.Collections.roster.reset(data)});
}
更新3:模型定義
App.Models.Contact = Backbone.Model.extend({
initialize: function() {
this.set({id: this.get('token')});
this.set({avatar: parseAvatar(this.get('avatar'))});
this.set({name: parseName(this.toJSON())});
this.set({view: new App.Views.Contact({model: this})});
},
defaults: {
username: ''
}
});
您需要使用View.el屬性才能使事件正常運行。
App.Collections.Contact = Backbone.Collection.extend({
initialize: function() {
this.bind('reset', function() {
console.log('COLLECTION RESET');
});
},
model: App.Models.Contact,
comparator: function(model) {
return model.get('name');
},
render: function() {
;
}
});
App.Views.Contacts = Backbone.View.extend({
el: '#contacts',
initialize: function() {
this.collection = new App.Collection.Contact;
this.collection.bind('reset', this.render, this);
var that = this;
socketRequest('friends', function(data) {
this.reset(data);
});
},
render: function() {
$(this.el).html('put your template here');
this.collection.each(this.addOne, this);
return this;
},
addOne: function(contact) {
var view = new App.Views.Contact({model: contact});
contact.view = view; // in case you need the ref on the model itself
$(this.el).append(view.render().el);
}
});
App.Views.Contact = Backbone.View.extend({
el: '',
tagName: 'div',
events: {
'click': 'select',
},
select: function(event) {
console.log('contact selected');
},
render: function() {
$(this.el).html(htmltmplContact(this.model.toJSON()));
return this;
}
});
對您的模型代碼有一點改進:
(注意,我刪除了視圖創建,這很重要!)
App.Models.Contact = Backbone.Model.extend({
parse: function(c) {
c.id = c.token;
c.avatar = parseAvatar(c.avatar);
c.name = parseName(c);
return c;
},
defaults: {
username: ''
}
});
並開始:
App.Views.roster = App.Views.Contacts;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.