Reputation: 14614
Here is my code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="someElement">
<button id="someButton">Click Me</button>
</div>
<script src="jquery-1.4.4.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script>
MyView = Backbone.View.extend({
events: {
"click #someButton": "clicked"
},
clicked: function (e) {
e.preventDefault();
alert("I was clicked!");
},
render: function () {
var html = "generate some HTML, here";
$(this.el).html(html);
}
});
$(function () {
var myView = new MyView();
myView.render();
$("#someElement").html(myView.el);
});
</script>
</body>
</html>
My question is: how do I wait for a click on the button to fire the click event?
(by the way, code partly comes from http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/ )
Upvotes: 2
Views: 324
Reputation: 370
An alternative to adding a jQuery click event would be to move the render method out of the jQuery onReady event and into the click-handler "clicked" that's already in your code. You just need to pass '#someElement' as your 'el' property when you create the view.
Made a quick jsBin demo here: http://jsbin.com/ugafod/4
This approach seems more "Backbone-ish" but both ways work fine.
Upvotes: 5
Reputation: 3186
You've used a self-invoking function. That's it nature - the browser will run the function as soon as it loads that part of the html page. If you want to defer it, you need to associate it with an action, such as:
$('my div or button or whatever you like').click(function(){
// Function to run here.
});
I've created a jsFiddle for you. This should be what you are after.
Upvotes: 1
Reputation: 9235
What button? Your render
event changes #someElement
content. Your button is gone before it can be clicked.
Upvotes: 2