骨干网,而不是" this.el"包皮 [英] Backbone, not "this.el" wrapping

查看:93
本文介绍了骨干网,而不是" this.el"包皮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个广泛使用的模板的,我喜欢使用的完全包含在的模板。我的意思是我想看到的模板的code所有的DOM元素包括的的之一,就像这样:

I do an extensive use of templates, and I like to use full contained templates. I mean that I want to see in the template code all the DOM elements including the root one, like this:

<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 code属性。我认为是丑陋和混乱。

And defining the root element and its attributes in the JS code. What I think is ugly and confusing.

因此​​,什么好办法避开我的骨干观为包装我的模板,一个额外的DOM元素?

我一直在检查这个问题主题:<一href=\"https://github.com/documentcloud/backbone/issues/546\">https://github.com/documentcloud/backbone/issues/546据我所知没有做任何正式的方式..但也许你可以给我推荐一个非官方的方式。

I have been checking this issue thread: https://github.com/documentcloud/backbone/issues/546 and I understand there is not any official way to do it.. but maybe you can recommend me a non official way.

推荐答案

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

You can take advantage of view.setElement to render a complete template and use it as the view element.

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

setElement view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one

您必须考虑两点:


  1. setElement 要求 undelegateEvents ,取查看事件的照顾,但要小心删除你可能所有其他事件已经为自己设定。

  2. setElement 元素没有注入到DOM,你必须处理自己。

  1. setElement calls undelegateEvents, taking care of the view events, but be careful to remove all other events you might have set yourself.
  2. setElement doesn't inject the element into the DOM, you have to handle that yourself.

这是说,你的观点可能看起来像这样

That said, your view could look like this

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/

这篇关于骨干网,而不是&QUOT; this.el&QUOT;包皮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆