javascript - backbone.js 事件

标签 javascript jquery 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);

知道为什么我无法触发事件吗?

最佳答案

你的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/

关于javascript - backbone.js 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884425/

相关文章:

javascript - 无法使用 ES6 导入语法

javascript - 如何使用 Sweet Alert 确认提交表单?

javascript - 带有 JQuery 函数的 Django 静态 Javascript 资源

javascript - Backbone.Collection.reset() 在 IE8 中抛出异常

javascript - Node.js 中的 Heredoc 用法

javascript - Google map 单击除 RichMarker 监听器之外的任何内容

javascript - 你怎样才能让动画越来越快?

javascript - 使用 jQuery 干燥 html?

jquery - 更改主干 Marionette CompositeView 中的集合

javascript - 避免 document.write?还有其他选择吗?