Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js turning off wrap by div in render

Tags:

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>?

like image 582
BazZy Avatar asked Oct 25 '11 18:10

BazZy


2 Answers

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);     } }); 
like image 195
kreek Avatar answered Oct 06 '22 00:10

kreek


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.

like image 31
Derick Bailey Avatar answered Oct 06 '22 00:10

Derick Bailey