Im creating a basic backbone app that should support multiple usrers, and i eould like my collection views to update for all users when any of thrm make a change to the collection.
I'm doing the following :
in my Views :
/*Collection view
- - - - - - -*/
App.Views.Contacts = Backbone.View.extend({
tagName: 'tbody',
wrapper : $('#contacttable'),
initialize: function() {
// custom events
vent.on('hideparent', this.hideMe,this);
vent.on('showparent', this.showMe,this);
// standard events
this.listenTo(this.collection, 'add', this.addOne);
this.listenTo(this.collection, 'reset', this.addAll);
this.listenTo(this.collection, 'all', this.render);
// Load the collection data
this.collection.fetch({reset:true});
},
render: function() {
// publish view status
vent.trigger();
// append the list view to the DOM
$('#contacttable').append(this.el);
return this;
},
addAll : function() {
this.collection.each( this.addOne, this);
},
addOne: function(model) {
var contactView = new App.Views.Contact({ model: model});
this.$el.append(contactView.render().el);
},
showMe: function() {
this.wrapper.show();
},
hideMe: function() {
this.wrapper.hide();
}
});
/*Single view
- - - - - - - */
App.Views.Contact = Backbone.View.extend({
tagName: 'tr',
template: template('singlecontact'),
events: {
'click a.delete' : 'deleteContact'
},
initialize: function() {
this.model.on('destroy', this.unrender, this); // doing this so item is only removed visually if its actually destroyed
this.model.on('change', this.render, this);
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
},
deleteContact: function(e) {
e.preventDefault();
this.model.destroy();
},
unrender: function() {
this.remove();
}
});
in my router :
this works for adding and editing but not deleting which is a problem 1. It also doesnt feel particularly right.
contactList: function() {
vent.trigger('app:contacts');
if (typeof App.AllContactsView == 'undefined') {
App.AllContactsView = new App.Views.Contacts({ //init method runs now
collection : App.contacts
});
// checking for updates
function updateContacts() {
App.AllContactsView.collection.fetch({merge:true });
}
setInterval(updateContacts, 1000);
} else {
App.AllContactsView.collection.fetch({add:true,remove:true});
}
ViewManagerTwo.showView(App.AllContactsView,true,false, false);
return App.AllContactsView;
},
is there a native way - ideally better than this to update the collections live?
Here's some info on using websockets as the transport layer in Backbone, which should get you going:
http://lostechies.com/derickbailey/2012/04/19/decoupling-backbone-apps-from-websockets/