I'm trying to run very simple view in backbone.js Here is the code:
(function($){
window.templateLoaderView = Backbone.View.extend({
events: {
'click #add_contact': 'loadTaskPopup'
},
initialize: function () {
alert('templateLoaderView - initialize');
_.bindAll(this, 'render');
},
render: function() {
alert('templateLoaderView - render');
},
loadTaskPopup: function() {
alert('templateLoaderView - loadTaskPopup');
}
});
})(jQuery);
$(document).ready(function() {
window.templateLoaderView = new templateLoaderView();
});
<div id="add_contact">CLICK HERE</div>
When page loads, it alerts this alert('templateLoaderView - initialize');, but when I click the div, nothing happens.
Could you please tell what I do wrong?
There are a couple of things that are going wrong.
this.el as a DIV but it isn't rooted in anything#add_contactrender because nothing is ever calling render. The most simple way to get your click handler to work is to tell the view which element to attach to:
window.templateLoaderView = new templateLoaderView({el: $("body") });
Going further...
Though, you may want your DIV to be created inside your view... it would go a little something like this:
(function($){
window.templateLoaderView = Backbone.View.extend({
template: _.template('<div id="add_contact">CLICK HERE</div>'),
events: {
'click #add_contact': 'loadTaskPopup'
},
render: function() {
$(this.el).html(this.template());
return this;
},
loadTaskPopup: function() {
alert('templateLoaderView - loadTaskPopup');
}
});
})(jQuery);
$(document).ready(function() {
window.templateLoaderView = new templateLoaderView();
$("body").append(window.templateLoaderView.render().el);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With