Proper way of doing view mixins in Backbone

The underscore.js library provides an extend method that does what you want. You can define functionality on any object, and then quite literally copy & paste all of the methods and attributes from that object to another. Backbone’s extend methods on Views, Models, and Routers are a wrapper around underscore’s extend. var MyMixin = { … Read more

Backbone: Refresh the current route

There are several things that would accomplish this. If you anticipate navigating to a route that is already in the url, then first check the current route fragment with Backbone.history.fragment and see if it is the same as the route you want to activate. If so, then you can do any of the following: You … Read more

Backbone.js event after view.render() is finished

I ran into this post which seems interesting var myView = Backbone.View.extend({ initialize: function(options) { _.bindAll(this, ‘beforeRender’, ‘render’, ‘afterRender’); var _this = this; this.render = _.wrap(this.render, function(render) { _this.beforeRender(); render(); _this.afterRender(); return _this; }); }, beforeRender: function() { console.log(‘beforeRender’); }, render: function() { return this; }, afterRender: function() { console.log(‘afterRender’); } });

Backbone, not “this.el” wrapping

You can take advantage of view.setElement to render a complete template and use it as the view element. setElement view.setElement(element) If you’d like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view’s delegated events from the old element to the … Read more

Backbone js .listenTo vs .on

listenTo is the newer and better option because these listeners will be automatically removed for you during stopListening which is called when a view gets removed (via remove()). Prior to listenTo there was a really insidious problem with phantom views hanging around forever (leaking memory and causing misbehavior) because view methods were referenced as event … Read more