我试图在给定集合中的模型更改被触发时实现一个动作,但是每当我尝试在我的集合上的 、 或 事件上放置一个侦听change
器add
时remove
,都不会触发任何事件。当我将更改事件附加到模型的initialize
函数(只是为了测试)时,该change
事件被成功触发。下面的视图本身不会更改代码,但我希望它在对集合进行更改时重新呈现自己。我的设置可能有问题,但我想听听您的建议。下面是我的代码:
contact.js(模型):
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var ContactModel = Backbone.Model.extend({
urlRoot: '/contacts'
});
return ContactModel;
});
联系人.js(集合):
define([
'jquery',
'underscore',
'backbone',
'models/contact'
], function($, _, Backbone, Contact){
var ContactCollection = Backbone.Collection.extend({
url: '/contacts',
model: Contact
});
return ContactCollection;
});
contactlist.js(查看):
define([
'jquery',
'underscore',
'backbone',
'text!templates/contactlist.html',
'collections/contacts'
], function($, _, Backbone, contactListTemplate, Contacts){
var ContactListView = Backbone.View.extend({
el: '.contact-list',
render: function(options) {
var that = this;
var contacts = new Contacts();
contacts.on("add", function() {
console.log('change');
});
contacts.fetch({
success: function(contacts) {
var results = contacts.models;
if (options.query || options.query === '') {
var results = [];
var query = options.query.toUpperCase();
for (var contact in contacts.models) {
if (contacts.models[contact].get('firstname').toUpperCase().indexOf(query) !== -1 ||
contacts.models[contact].get('lastname').toUpperCase().indexOf(query) !== -1 ||
contacts.models[contact].get('email').toUpperCase().indexOf(query) !== -1 ||
contacts.models[contact].get('phonenumber').toString().toUpperCase().indexOf(query) !== -1)
{
results.push(contacts.models[contact]);
}
}
options.idclicked = null;
}
if (!options.idclicked && results[0]) {
options.idclicked = results[0].get('id');
Backbone.history.navigate('/contacts/' + results[0].get('id'), {trigger: true});
}
var template = _.template(contactListTemplate, {contacts: results, idclicked: options.idclicked});
that.$el.html(template);
$(document).ready(function() {
$('.contact-list').scrollTop(options.scrolled);
});
}
});
},
events: {
'click .contact': 'clickContact'
},
clickContact: function (ev) {
$('.contact-clicked').removeClass('contact-clicked').addClass('contact');
$(ev.currentTarget).addClass('contact-clicked').removeClass('contact');
window.location.replace($(ev.currentTarget).children('a').attr('href'));
}
});
return ContactListView;
});