I have a view I want to insert into the DOM. As I understand it, the setElement method creates a jQuery element (saved as $el) which is unattached to the DOM. I'm trying to insert that jQuery element into an existing DOM element, without success.
SimpleView = Backbone.View.extend({
initialize: function(){
this.setElement('#simpleview');
this.render();
},
render: function(){
this.$el.appendTo('#container');
}
});
var myview = new SimpleView();
What am I missing?
I think you misunderstand how setElement
works. When you call setElement
, you're supposed to give it a DOM element that already exists and then setElement
does three things:
el
to the element.el
and binds the view's events to the new el
.el
in $el
.You seem to be calling setElement
to try to create a new element with id="simpleview"
. You probably just want to include id: 'simpleview'
in the view definition since
this.el
is created from the view'stagName
,className
,id
andattributes
properties, if specified. If not, el is an emptydiv
.
You should get what you're looking for if your view looks more like this:
SimpleView = Backbone.View.extend({
id: 'simpleview',
initialize: function(){
this.render();
},
render: function(){
this.$el.appendTo('#container');
}
});
Updated fiddle: http://jsfiddle.net/ambiguous/7GPEy/