Backbone.js事件未被触发

时间:2012-02-22 21:45:35

标签: javascript backbone.js

我尝试将Backbone.js用于我的一个项目,但是使用视图事件时遇到了问题。

HTML文件:

<html>
    <head>
        <script type="text/javascript" src="underscore-min.js"></script>
        <script type="text/javascript" src="backbone-min.js"></script>
        <script type="text/javascript" src="model.js"></script>
    </head>
    <body>
        <div id="app">
        </div>
    </body>
</html>

model.js代码是

window.onload = function() {
    var MyModel = Backbone.Model.extend({
        defaults: {
            name: "Test"
        }
    });

    var MyView = Backbone.View.extend({
        tagName: "li",
        events: {
            "click li": "Show"
        },
        render: function() {
            this.el.innerHTML = this.model.get("name");
        },
        Show: function() {
            alert(this.model.get("name"));
        }
    });

    var model = new MyModel();
    var view = new MyView({model: model});
    view.render();

    document.getElementById("app").appendChild(view.el);
}

我没有错误,但“li”点击时不会触发“显示”功能。有什么问题?

1 个答案:

答案 0 :(得分:2)

问题是你将click事件绑定到(不存在的)&#34;&#34;元素的子元素,而不是li元素本身。试试这个:

var MyView = Backbone.View.extend({
    tagName: "li",
    events: {
        "click": "Show"
    },
    render: function() {
        this.el.innerHTML = this.model.get("name");
    },
    Show: function() {
        alert(this.model.get("name"));
    }
});