尝试设置一个基本的 backbone.js 示例 - 无法触发事件。我错过了什么?
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>
这是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);
知道为什么我无法触发事件吗?
最佳答案
你的render
方法杀死了#sayhello
:
render : function() {
console.log("rendering");
$(this.el).html("Hello world"); // #sayhello is now gone
}
因此没有可点击的#sayhello
,您的事件处理程序永远不会被调用。
也许您的render
应该看起来更像这样:
render: function() {
console.log("rendering");
$(this.el).find('button').html("Hello world");
}
关于javascript - backbone.js 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884425/