Search code examples
javascriptbackbone.jsbackbone-views

Possible to extend multiple views in Backbone?


I have 3 backbone views (Month, Day, Week).

There is some common code all 3 share that I'll put in a Base view.

Then there is some common code that Day & Month share which I'll put in a DayAndMonthBase view and other common code that Day & Week share which I'll put in a DayAndWeekBase view. Both the DayAndMonthBase and the DayAndWeekBase will extend the Base.

Finally, my Month view will extend DayAndMonthBase and my Week view will extend my DayAndWeekBase. However with my Day view, how can I extend BOTH the DayAndMonthBase view as well as the DayAndWeekBase view?


Solution

  • I like to solve this sort of problem using mixins rather than inheritance, because there is no clear hierarchical structure here. Constructs like DayAndMonthBase along with DayAndWeekBase are rigid and inextensible. What i like to do is define the common behavior as objects, and then inject the behavior into the views using _.extend and not Backbone.View.extend.

    Define your mixin objects

    var mixin1 = {
        ....
    }
    
    var mixin2 = {
        ....
    }
    
    var mixin3 = {
        ....
    }
    

    Then inject these mixins into each View that needs the functionality.

    var Day = Backbone.View.extend({
        ....
    })
    _.extend(Day.prototype, mixin1);
    _.extend(Day.prototype, mixin2);
    _.extend(Day.prototype, mixin3);
    
    
    var Week = Backbone.View.extend({
        ....
    })
    _.extend(Week.prototype, mixin1);
    
    
    var Month = Backbone.View.extend({
        ....
    })
    _.extend(Month.prototype, mixin2);
    

    It's easier to reason about this way, because you don't have the mental load of remembering what DayAndWeekBase actually does. If you name your mixins appropriately, it's clear to see what kind of functionality you're injecting into the views.