Backbone, not “this.el” wrapping

前端 未结 3 1425
遇见更好的自我
遇见更好的自我 2020-11-27 17:21

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 element

3条回答
  •  暖寄归人
    2020-11-27 18:16

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

    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

    Two points you have to account for:

    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;
        }
    });
    

    And a working example to play with http://jsfiddle.net/gNBLV/7/

提交回复
热议问题