I am trying to implement an action when a change to a model in a given collection is fired, but whenever I try to put a listener on the change
, add
, or remove
events on my collection, no events are fired. When I attached a change event to a model's initialize
function (just to test), the change
event was fired successfully. The view below doesn't itself change the code, but I want it to re-render itself whenever a change to the collection has been made. It could be something wrong with my setup, but I want to get your advice. Below is my code:
contact.js (Model):
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var ContactModel = Backbone.Model.extend({
urlRoot: '/contacts'
});
return ContactModel;
});
contacts.js (Collection):
define([
'jquery',
'underscore',
'backbone',
'models/contact'
], function($, _, Backbone, Contact){
var ContactCollection = Backbone.Collection.extend({
url: '/contacts',
model: Contact
});
return ContactCollection;
});
contactlist.js (View):
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;
});