Backbone, not “this.el” wrapping

前端 未结 3 1403
遇见更好的自我
遇见更好的自我 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:11

    Now you can also define a view's tagName as a function and create a class like this:

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

    Here's a working example

    0 讨论(0)
  • 2020-11-27 18:15

    Backbone.Decarative.Views provides you with an alternative way to do this, without having to rely on setElement. For more, check out my answer here.

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题