Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of doing view mixins in Backbone

Tags:

backbone.js

I extend base backbone views all the time and have a base view per section so that I can extend on multiple levels. My question is, what's the most effective way of doing view mixins: reusable view partials that can be mixed in to any view. For example:

var BaseProfile = Backbone.View.extend({ ...});
var UserProfile = BaseProfile.extend({ ...});
var VideoSupport = Backbone.View.extend({ ...});

What's the best way to mixin VideoSupport view (an event object and a few methods) with UserProfile view?

like image 381
Mauvis Ledford Avatar asked Oct 21 '11 18:10

Mauvis Ledford


4 Answers

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"
like image 141
Derick Bailey Avatar answered Nov 20 '22 01:11

Derick Bailey


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.

like image 26
Dan S Avatar answered Nov 20 '22 01:11

Dan S


you can use this gist https://gist.github.com/3652964

like image 3
user873792 Avatar answered Nov 20 '22 02:11

user873792


You can use Backbone.Mix library which used mixins embedded to the prototype chain

var Editable = {
    edit: function(){
        console.log('edit');
    }
};

var Article = Backbone.Model.mix(Editable).extend({
    initialize: function(){
        Backbone.Model.prototype.initialize.call(this);
        this.edit(); // logs "edit"
    }
});
like image 3
jifeon Avatar answered Nov 20 '22 02:11

jifeon