Have som trouble getting the code below to work.
I am trying to fire an event from a rendered sub view that has its own events object.
Is it possible to do this in an easy way?
var SubView = Backbone.View.extend({
events: {
'click .subview-item a': 'test'
},
el: '#subview',
test: function() {
console.log('please print this...');
},
initialize: function() {
this.template = '<div class="subview-item"><a href="#">Clickable Subview</a></div>'
},
render: function(){
$(this.el).html(_.template(this.template));
return this;
}
});
var MainView = Backbone.View.extend({
el: $('#content'),
initialize: function(){
this.template = '<h1>Hello</h1><div id="subview"></div>';
this.subView = new SubView();
},
render: function(){
$(this.el).html(_.template(this.template));
this.subView.render();
return this;
}
});
var mainView = new MainView({});
mainView.render();
Any ideas??
When you create your
subViewinsideMainView‘sinitialize, the#subviewelement does not yet exist in your DOM, since you have not yet rendered MainView. So a new<div>is created outside the DOM. You need to first renderMainViewbefore creating theSubView. You could do that inside theMainView‘srender()but the following is simpler I think:Also took the liberty to correct a few things like using
this.$eland creating the template oninitialize()rather than recompiling on everyrender().