骨干,而不是“this.el”包装(Backbone, not “this.el” wrapping

2019-06-17 12:20发布

我做了一个广泛使用模板 ,我喜欢用全包含模板。 我的意思是我要在模板代码的所有DOM元素,包括一个,这样看:

<script type="text/template" id="template-card">
  <div class="card box" id="card-<%= id %>">
    <h2><%= title %></h2>
    <div><%= name %></div>
  </div>
</script>

但是骨干喜欢的是具有这样一个模板

<script type="text/template" id="template-card">
  <h2><%= title %></h2>
  <div><%= name %></div>
</script>

并限定元素以及它在JS代码属性。 我认为是丑陋和混乱。

因此, 任何好的办法来避免我的骨干观为包装我的模板有额外的DOM元素?

我一直在检查这个问题线程: https://github.com/documentcloud/backbone/issues/546 ,我知道没有做任何正式的方式..但也许你可以给我推荐一个非官方的方式。

Answer 1:

您可以利用的view.setElement呈现一个完整的模板,并把它作为视图元素。

setElement view.setElement(元件)
如果你想用骨干视图适用于不同的DOM元素,使用setElement,这也将创造缓存$ EL参考和从旧元素移动视图的委托事件到新的

两点你必须考虑:

  1. setElement呼吁undelegateEvents ,取查看事件的护理,但要小心删除您可能已经为自己设定的所有其他事件。
  2. setElement不喷射元素到DOM,你必须处理自己。

这就是说,你的观点看起来是这样的

var FullTemplateView = Backbone.View.extend({

    render: function () {
        var html, $oldel = this.$el, $newel;

        html = /**however you build your html : by a template, hardcoded, ... **/;
        $newel = $(html);

        // rebind and replace the element in the view
        this.setElement($newel);

        // reinject the element in the DOM
        $oldel.replaceWith($newel);

        return this;
    }
});

而一个工作示例一起玩http://jsfiddle.net/gNBLV/7/



Answer 2:

现在,你还可以定义视图的标记名的函数,创建这样一个类:

var MyView = Backbone.View.extend({
   template: '#my-template',
   tagName: function() {
     // inspect the template to retrieve the tag name
   },
   render: function() {
     // render the template and append its contents to the current element
   }
});

这里有一个工作例子



Answer 3:

Backbone.Decarative.Views为您提供了一种替代的方式来做到这一点,而不必依赖于setElement 。 如需更多信息,请查看这里我的答案 。



文章来源: Backbone, not “this.el” wrapping
标签: backbone.js