Backbone.js查看事件未启动

Backbone.js View Event Not Firing

本文关键字:启动 事件 js Backbone      更新时间:2023-09-26

我在启动backbone.js视图事件时遇到问题。当我点击#登录按钮时,什么都没有发生。

我也在使用iCanHaz(http://icanhazjs.com/)以加载模板。

这是我的javascript:

$(function() {
 var router = new App.Router;
 Backbone.history.start();
});
App.Router = Backbone.Router.extend({
 routes: {
    "login": "login"
 },
login: function() {
    var view = new App.Views.LoginView;
 }
});
App.Views.LoginView = Backbone.View.extend({
 el: '#login',
 initialize: function() {
    _.bindAll(this, 'render', 'validateLogin');
    this.render();
 },
 render: function() {
    App.Stage.html(ich.loginView());
 },
 events: {
    'click button#login-button' : 'validateLogin'
 },
 validateLogin: function(event) {
     console.log("validateLogin fired.");
 }
});

这是我的标记(使用ICanHaz.js):

<script id="loginView" type="text/html">
        <div data-role="page" id="login" class="container">
            <div class="hero-unit">
                <div class="row-fluid">
                    <div class="span12">
                        <div class="form-horizontal">
                        <fieldset>
                            <legend>Please login to continue</legend>
                            <div class="control-group">
                            <label class="control-label" for="username">Username</label>
                            <div class="controls">
                                <input type="text" class="input-xlarge" id="username">
                            </div>
                            </div>
                                <div class="control-group">
                            <label class="control-label" for="password">Password</label>
                            <div class="controls">
                                <input type="password" class="input-xlarge" id="password">
                            </div>
                            </div>
                                <div class="form-actions">
                        <button id="login-button" class="btn btn-primary btn-large">Login</button>
                    </div>
                        </fieldset>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </script>

我想明白了。Backbone在创建el之前将事件绑定到el。在异步iCanHaz调用的回调中,我使用了这个.setElement('#login'),它运行得很好。来自backbone.js文档:

setElement [view.setElement(element)]

"如果您想将Backbone视图应用于不同的DOM元素,请使用setElement,它还将创建缓存的$el引用,并将视图的委派事件从旧元素移动到新元素。"

我认为您没有正确使用View的'el'属性。尝试让属性引用jQueryDOM对象,而不仅仅是ID,如下所示:

App.Views.LoginView = Backbone.View.extend({
 el: $('#login')
...