Search code examples
javascriptmarionette

Triggers and ui sections subclassing View subclasses


I couldn't find a question about this subject although I guess someone would have faced this problem before. Excuse me if I'm re-posting.

I have a problem with a component I'm creating. Imagine component implemented as a ItemView that defines certain elements from it's UI as a "View.ui" hash.

What happens if I want to create an specialized version of that component by subclassing it and add extra ui element definitions? What I'm getting here is that new definitions overwrite the parent ones, so the parent functionality breaks.

Is there any common solution to workaround this issue?

The only one that comes to my mind is tweaking the ".extend" functionality for base Marionette View class in order to treat specially these "ui" and "triggers" attributes when subclassing, using something more like a ".merge" instead of a "_.extend".

Any other thoughts?

thanks in advance,


Solution

  • You can use _.extend in the inheriting objects constructor to merge the hashes.

    fiddle: http://jsfiddle.net/puleos/zkBCm/

    var ParentView = Backbone.Marionette.ItemView.extend({
        ui: {
            link : 'a',
            checkbox : "input[type=checkbox]"
        }
    });
    
    var ChildView = ParentView.extend({
        ui: {
            list : 'ul'
        },
        constructor: function(options) {
            var args = Array.prototype.slice.apply(arguments);
            ParentView.prototype.constructor.apply(this, args);
            this.ui = _.extend(this.ui, ParentView.prototype.ui);
        }
    });
    
    var parentView = new ParentView();
    var childView = new ChildView();
    
    console.log('parent', parentView.ui); // Returns link & checkbox
    console.log('child', childView.ui);   // Returns ul, link & checkbox