When I'm appending my template to the body, the el and $el do not work. For example, consider this view that renders the template onto the body:
var MyView = Backbone.View.extend({
el: "#main-menu",
initialize: function(){
this.render();
},
events: {
"click": "clickHandler"
},
render: function(){
$("body").append( '<div id="main-menu" style="width:50px;height:50px;background-color:red;"></div>' );
},
clickHandler: function(){
alert("test");
}
});
I render the div containing the #main-menu element after it's already defined for the el. Whenever I try to use the el or any of the events it doesn't work. An option would be to set the el to body but for some reason that seems wrong to me since that's not really my element and I would have to write #main-menu in all the click handlers.
Thoughts?
You are basically telling backbone that your el
is the element with id main-menu that should already exist in the page. However you are adding the element with that id in the render function! You would need to manually reset the view element with this.setElement($("#main-menu"));
which is quite ugly.
You have 2 options:
Create and add to the page the main-menu
element before the view is created, which allows you to define your view in a similar way as you had:
var MyView = Backbone.View.extend({
el: "#main-menu",
initialize: function(){
this.render();
},
events: {
"click": "clickHandler"
},
render: function(){
this.$el.append('<p>Some menu contents</p>' );
},
clickHandler: function(){
alert("test");
}
});
$("body").append( '<div id="main-menu"></div>');
var view = new MyView();
You can check it on this fiddle
Don´t set el in your view and let backbone to create an element taking into account the id
, tagName
, className
and attributes
properties of your view. Then once your view is created, you can insert its $el
into the page.
var MyView = Backbone.View.extend({
id: "main-menu",
initialize: function(){
this.render();
},
events: {
"click": "clickHandler"
},
render: function(){
this.$el.append('<p>Some menu contents</p>');
},
clickHandler: function(){
alert("test");
}
});
var view = new MyView();
$("body").append(view.$el);
You can give it a try on this other fiddle