Trying to set up a basic backbone.js example - can't get events to fire. What am I missing?
HTML
<html lang="en">
<head>
<script type="text/javascript" src="js/libs/jquery/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/libs/underscore/underscore-min.js"></script>
<script type="text/javascript" src="js/libs/backbone/backbone.js"></script>
<script type="text/javascript" src="js/test.js"></script>
<title></title>
</head>
<body>
<div id="helloworld">
<button id="sayhello">
Say Hello
</button>
</div>
</body>
And here is JS
(function($) {
HelloWorldView = Backbone.View.extend({
el : '#helloworld',
events: {'click #sayhello': 'onButtonClicked'},
onButtonClicked: function()
{
console.log("buttonclicked");
},
render : function() {
console.log("rendering");
$(this.el).html("Hello world");
}
});
var helloView = new HelloWorldView().render();})(jQuery);
Any idea why I can't get the events to fire?
Your render method kills #sayhello:
render : function() {
console.log("rendering");
$(this.el).html("Hello world"); // #sayhello is now gone
}
So there is no #sayhello to click on and your event handler never gets called.
Perhaps your render is supposed to look more like this:
render: function() {
console.log("rendering");
$(this.el).find('button').html("Hello world");
}
Demo: http://jsfiddle.net/ambiguous/4empG/
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