Reputation: 14868
I've been looking at backbone.js tutorials for a couple of hours now and can't make my mind up if it's a good fit for what I want to achieve without investing some serious time to find out.
My app is largely based around one page and fairly AJAX heavy. This page has several UI elements on it that are polling the server and updating themselves independently. In addition, there is a central polling mechanism looking for events that may trigger an update on any of the other UI components.
What I'm considering is aggregating all of these independent URLs into one, and having my front end listen out on that URL only, then delegate each event to the appropriate UI element. Effectively, it would be a bit like a Message Bus for my front end.
Sound like a reasonable use of backbone? Or have I missed the point of it?
Upvotes: 3
Views: 751
Reputation:
Backbone should work fine for this case.
Create a central event poller. This fetch all types of events from server and publish them to the rest of the application (not tested):
var EventPoller = Backbone.model.extend({
url: "events/",
poll: function(){
this.fetch({
success: function(self, response){
self.handleEvents(response);
self.poll();
}, error: function(self){
self.poll();
}
})
},
handleEvents: function(events){
var self = this;
$(events).each(function(index, event){
self.trigger(event.name, event.data);
});
}
});
Then you can let several models listen for these events:
var StockModel = Backbone.Model.extend({
initialize : function() {
this.poller.bind('stockChange', this.changeStock, this);
},
changeStock: function(stock){
this.set({name: event.name});
}
});
And finally let a view listen for changes in the model:
var StockView = Backbone.View.extend({
initialize : function() {
this.model.bind('change:name', this.updateStock, this);
//this.poller.bind('stockChange', this.updateStock, this); //you could also listen for poll events directly in view with out having a model for each view.
},
updateStock: function(){
$(this.el).html(model.get("name"));
}
});
To setup the poller and the views:
var eventPoller = new EventPoller();
var stockModel = new StockModel({poller: eventPoller})
var stockView = new StockView({model:stockModel});
eventPoller.poll();
A general advice is that backbone take some days effort learning, but if you read documentation and follows some basic examples you will get up to speed.
Maybe the most confusion thing with backbone is this
. I would recommend to use firebug and debug trough the application to see how this
changes.
Upvotes: 3
Reputation: 37466
Backbone would work, but I would also check ember.js, also known as sproutcore 2.0, backbone is too verbose for my taste, ember.js kinda takes care of that, check http://www.emberjs.com/.
Upvotes: 0