扩展视图时如何附加classNames / attributes

时间:2015-01-05 04:57:34

标签: backbone.js marionette

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


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

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

如何制作MyView2 =
<div class="MyView1 MyView2" data-xxx="MyView1" data-yyy="MyView2">

如果不可能,这也没关系 MyView1 = <div class="MyView1" data-view="MyView1"
MyView2 = <div class="MyView1" data-view="MyView1" data-another-attrib="MyView2">

1 个答案:

答案 0 :(得分:6)

className可以定义为函数并在运行时进行评估。来自the Backbone docs

  

如果要等到将值定义到运行时,也可以将tagName,id,className,el和events等属性定义为函数。

因此,您可以查找父类className的结果并将新类附加到其中。请确保使用_.result来评估父级的className,因为它也是一个函数。

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

或者,你可以将这两个类添加到MyView2&#39; className

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

更新 - 来自评论。你也可以从MyView1中挖出className

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