Backbone js: How to remove extra tag in view?

后端 未结 2 989
小鲜肉
小鲜肉 2020-12-06 06:42

I have the following template:

....

and the following view:



        
相关标签:
2条回答
  • 2020-12-06 07:36

    Change your template to get rid of the outer div:

    <div></div>
      ....
    

    Then, tell the view to create the div with a class name:

    tagName: "div",
    className: "row"
    

    OR if you want to keep the current template, then tell the View which el to use (assuming it exists already some place on your page):

    var testView = new TestView({el: $(".row")});
    

    EDIT You asked if you can do this in the initializer? Sure, but you'd need to make sure that you hook the events:

    initialize: function () {
        this.el = $(".row");
        this.delegateEvents();
        _.bindAll(this, 'clickbtn');
    }
    

    Honestly, though, the first two options are more de-coupled IMO.

    0 讨论(0)
  • 2020-12-06 07:40

    Another option that does not require modifying the template is to use setElement

    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.

    This will allow you to completely bypass tagName. You can leave tagName out of your View definition (it defaults to div anyways). You also do not have to worry about manually delegating your events or require that an element selector is known beforehand as referred to in the answer by @Brian Genisio, although those other methods will work too.

    render: function () {
        this.setElement(this.template(this.model.toJSON()));
        return this;
    }
    
    0 讨论(0)
提交回复
热议问题