How to avoid template wrapping with empty div in Backbone?

前端 未结 6 2002
死守一世寂寞
死守一世寂寞 2020-12-11 15:13

When I create view backbone creates empty div-container if el is not set. Template (this.$el.html(this.template(this.model.toJSON()))) inserted in that div. How

6条回答
  •  爱一瞬间的悲伤
    2020-12-11 15:27

    I have had this same problem with Backbone. In my opinion it is a design flaw. Here is a Reddit post describing some of the solutions possible: http://www.reddit.com/r/javascript/comments/11pkth/how_do_you_render_your_backbonejs_views/

    Here is Jeremy Ashkenas' take on the issue:

    | If I want to completely encapsulate the HTML inside of my template, without creating any extra divs, | I must replace this.el. At least as far as I know. Is there any better way to do this?

    Give up your desire to do that, and you'll have a much easier time ;) A big part of the point of Backbone always providing a view's element ("el") for you, is that your events are valid at all times -- regardless of whether the view is in the DOM, if the data is ready yet, or if the template is available. It's a more stateless way to declare your mouse and keyboard events, relying less on the required ordering of your rendering. If you really want to replace a view's element, use setElement. But it's not recommended, or necessary.

提交回复
热议问题