Search code examples
javascriptbackbone.jsbackbone-viewsmixins

Using mixins in backbone views -which of these is the better approach?


Both of these options result in correct behaviour of the views. This question is more about which approach is more efficient, or desirable for other reasons.

If there are other ways to accomplish this, please let me know about them too!

Option #1

Extend within the initialize function of the backbone view.

define([

    'mixins/fooMixin',

    'mixins/barMixin'

],

function(FooMixin, BarMixin) {

    var FooBarView = BackboneLayout.extend({

        initialize: function() {

            _.extend(this, FooMixin);

            _.extend(this, BarMixin);

            /* do other things */

        },

        mySpecialMethod: function() {

            this.foo();

            this.bar();

        }

    });

    return FooBarView;

});

Option #2

Extend on a plain ol' javascript object prior to creating the backbone view.

define([

    'mixins/fooMixin',

    'mixins/barMixin'

],

function(FooMixin, BarMixin) {

    var FooBarViewDefn = {};

    _.extend(FooBarViewDefn, FooMixin, BarMixin, {

        initialize: function() {

            /* do other things */

        },

        mySpecialMethod: function() {

            this.foo();

            this.bar();

        }

    });

    return BackboneLayout.extend(FooBarViewDefn);

});

Solution

  • nr 2, no doubt, since it will only run once and #1 will be executed every time the view is instantiated.