Search code examples
backbone.jsmarionette

How to append classNames/attributes when extending views


var MyView1 = Marionette.ItemView.extend({
   className: "MyView1",
   attributes: { 'data-view': 'MyView1' }
});


var MyView2 = MyView1.extend({
   className: "MyView2",
   attributes: { 'data-view': 'MyView2' }
});

MyView1 is <div class="MyView1" data-view="MyView1">
MyView2 is <div class="MyView2" data-view="MyView2">

How to make MyView2 =
<div class="MyView1 MyView2" data-xxx="MyView1" data-yyy="MyView2">?

If impossible, this is also ok
MyView1 = <div class="MyView1" data-view="MyView1"
MyView2 = <div class="MyView1" data-view="MyView1" data-another-attrib="MyView2">


Solution

  • className can be defined as a function and evaluated at runtime. From the Backbone docs:

    Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime.

    So you could look-up the result of the parent class's className and append the new class to it. Make sure you use _.result to evalutate the parent's className incase it is also a function.

    var MyView2 = MyView1.extend({
       className: function(){
           return _.result(MyView2.__super__, 'className') + " MyView2";
       },
       attributes: { 'data-view': 'MyView2' }
    });
    

    Alternatively, you could just add the two classes to MyView2's className:

    var MyView2 = MyView1.extend({
       className: "MyView1 MyView2",
       attributes: { 'data-view': 'MyView2' }
    });
    

    Update - from the comments. You can also dig out the className from MyView1 as well:

    var MyView2 = MyView1.extend({
       className: MyView1.prototype.className + " MyView2",
       attributes: { 'data-view': 'MyView2' }
    });