2011-10-25 33 views
3

试图设置一个基本的backbone.js示例 - 无法触发事件。我错过了什么?与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); 

任何想法,为什么我不能让事件火?

回答

3

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"); 
} 

演示:http://jsfiddle.net/ambiguous/4empG/

+0

感谢您指出,但我仍然无法捕获onButtonClicked事件? –

+1

@Andrei:这个演示(http://jsfiddle.net/ambiguous/4empG/)的工作原理是什么,你在做什么不同?我在演示中做出的唯一更改就是在我的答案中提供了新的'render'。 –

+0

这很奇怪,当我将我的本地代码粘贴到JSFiddle中时它工作正常;本地没有这种运气。 HTML与上面的完全一样... –

0

其实你的 “Hello World”
$(this.el)的.html替换整个HTML( “你好,世界”);
它更好,你只需找到按钮并更改html。
this。$('#sayhello')。html('Hello World');