使用Backbone / Marionette视图实例时,可以避免多个具有相同ID的DOM元素吗?

时间:2014-01-07 05:12:56

标签: marionette

当我创建Marionette视图的多个视图实例时,这个视图实例与带有id的模板html链接,这些视图的多个实例将会重复这些实例。

虽然它正常工作,但我觉得应该有更多的架构正确的方法。

示例代码如下所示。

Template:
<script id="myTemplate" type="text/template">
    <div id="myDiv">
        <input type="text" id="myText"/>
        <input type="button" id="myBtn" value="Click me!"/>
    </div>
</script>
View:
MyView = Backbone.Marionette.ItemView.extend({
    template: '#myTemplate',
    events: {
        'click #myBtn' : 'myFunc'       //Correctly identifies its own 'myBtn'
    },
    myFunc : function() {
        alert($('myText').val());     //Again, picks own 'myText'
    }
});
var v1= new MyView();
v1.render();
var v2= new MyView();
v2.render();     //Duplicate IDs now present in DOM

我需要一些这些DOM元素的唯一标识,因此需要ID。 即使将模型绑定到此视图,我们也需要一些方法来识别这些DOM元素。

在不重复ID的情况下执行此操作的正确方法是什么。

3 个答案:

答案 0 :(得分:1)

创建时只需将id传递给视图:

模板:

<script id="myTemplate" type="text/template">
    <input type="text" class="js-myText"/>
    <input type="button" class="js-myBtn" value="Click me!"/>
</script>

查看def:

MyView = Backbone.Marionette.ItemView.extend({
    template: '#myTemplate',
    events: {
        'click #myBtn' : 'myFunc'       //Correctly identifies its own 'myBtn'
    },
    myFunc : function() {
        alert($('myText').val());     //Again, picks own 'myText'
    }
});

Instanciation:

var v1= new MyView({ id: "view" + number});
v1.render();

然后,您可以为视图提供动态id值(例如,使用模型ID)。

也就是说,当使用木偶时,您不需要致电render:您应该show在区域内查看视图。请查看free sampleMarionette book,以加快速度。

答案 1 :(得分:0)

如果您必须使用唯一ID以确保没有人在视图中意外复制类名,您可以使用:

  1. Underscore的uniqueId方法为视图中的每个DOM元素生成唯一ID,例如:<input type="text" id= <%= _.uniqueId("myText_") %> />这样可以确保ID不会重复。但如果您需要通过这些ID识别元素,它们就没有用处。

  2. Marionette的TemplateHelpers允许您在模板中使用辅助函数:

    //Define this inside your view:
      templateHelpers: function() {  
          var that = this;
          return {  
             getIdSuffix : function() {  return that.idSuffix; }
                /*Where idSuffix is passed to the view during instantiation
                  and assigned to this.idSuffix */   
          };  
      }
    
    //In the template:
      <input type="text" id= <%= "myText_" + getIdSuffix() %> />
    
  3. 您现在可以在运行时知道您将拥有哪些DOM ID,前提是不要将相同的idSuffix提供给多个视图实例。

答案 2 :(得分:0)

简单地说,如果它不是唯一的,请不要使用id。使用类或其他方式识别元素。

您可以使用任何jQuery选择器来定位您想要的元素,范围从疯狂和脆弱:

this.$('div > input:first'); // don't actually do this!

更慢但语义更好:

this.$('[data-element-type="some-text-box-descriptive-name"]');

虽然实际上,使用类是最好的,因为这是一个类的用途 - 用于识别元素的类型。我可以看到维护者可能不知道不在模板中更改您的类,因此数据属性可能是可接受的,甚至可能是(在这种情况下):

this.$('input[type=text]');