Backbone.js turning off wrap by div in render

2019-01-22 03:18发布

问题:

I have model Post and collection Posts. And want to make form with list of all post in <select id="multi" multiple="multiple">. So i have to make a PostView render inside my #multi with just this template:

<option value=""><%= title %></option>

But finally I get it wrapped with div. Is there any solution for not wrapping this template with <div>?

回答1:

If you don't define an el (or tagName) for the view (in the class or during instantiation) the view will be placed inside a div tag. http://documentcloud.github.com/backbone/#View-el

var PostView = Backbone.View.extend({
  tagName: 'option'
});

UPDATE

Starting v0.9.0, Backbone has view.setElement(element) to get this done.

var PostView = Backbone.View.extend({
    initialize: function() {
        var template = _.template('<option value=""><%= title %></option>');
        var html = template({title: 'post'});
        this.setElement(html);
    }
});


回答2:

If you don't want to have the view wrap your HTML, you'll have to do a few things:

  1. Replace this.el entirely
  2. Call delegateEvents on the new el
render: function(){
  var html = "some foo";
  this.el = html;
  this.delegateEvents(this.events);
}

Since Backbone generates a div or other tag (based on your tagName setting for the view), you have to replace it entirely. That's easy to do. When you do that, though, you lose your declared events because Backbone uses jQuery's delegate under the hood to wire them up. To re-enable your declared events, call delegateEvents and pass in your events declarations.

The result is that your view.el will be the <option> tag that you want, and nothing more.



回答3:

In version 0.9.0, Backbone introduced view.setElement(element) to handle this operation.