Proper way of doing view mixins in Backbone
Solution 1:
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 = {
foo: "bar",
sayFoo: function(){alert(this.foo);}
}
var MyView = Backbone.View.extend({
// ...
});
_.extend(MyView.prototype, MyMixin);
myView = new MyView();
myView.sayFoo(); //=> "bar"
Solution 2:
I might recommend using Backbone.Cocktail which provides a really succinct way of specifying mixins (that respect inheritance):
var Mixin = {
initialize: function() {
console.log("I'll be called as well as the class's constructor!");
}
};
var View = Backbone.View.extend({
mixins: [ MyMixin ]
});
I've detailed it in this blog post.