Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

5/21/2013

Triggering globally custom events in Backbone

If you want to implement traditional publish/subscribe pattern, you can do a very cool trick with Backbone custom events model.

// create a basic model
var Model = Backbone.Model.extend({
    defaults: {
        color:"red",
        name: "bmw"
    }
});

// create a view for that model
var ModelView = Backbone.View.extend({
tagName: "h4",
initialize: function(){
    this.render();
},
render: function(){
    this.$el.html(this.model.get("color"));
    return this;
}
});

// create a route
var Route = Backbone.Router.extend({
    routes: {
    "home": "showHome"
},
showHome: function(){
    Vent.trigger("init");
}
});

// create instances
var model = new Model;
var modelView = new ModelView({model:model});
new Route;

// start a history
Backbone.history.start();

// create a global Vent object, and extend it with Backbone event model (with the help //of underscore.js - which is Backbone dependency ):
var Vent = _.extend({},Backbone.Events);

// append everything to the DOM, with the help of custom global event:
Vent.on("init",function(){
$(document.body).append(modelView.el);
});

The most important part of this code is attaching custom event handler to the URL route. We made that event  globally accessible, by attaching it to the global Vent object. Vent object is triggering custom init event , which is responsible for appending content the DOM.  We subscribed to that custom Init event  through on method of the global Vent object. This is very basic example, just to show the power of custom events.

Happy coding.



No comments:

Post a Comment