0

我有这样的代码。我点击按钮,它只工作几次。Chrome 说按钮上没有事件监听器。但是 View 创建按钮并且 View 有 click 事件。你能帮助我吗?

//buttons view
var NavigateBar = Backbone.View.extend({    
    events : {
        'click button#back' : 'onBack',
        'click button#next' : 'onNext',
        'hover' : function() {console.log('hover on navigate')}
    },
    initialize: function(options) {
//buttons html
        this.backDiv = '<button id="back" class="btn btn-primary btn-large pull-left">Back</button>';
        this.nextDiv = '<button id="next" class="btn btn-primary btn-large pull-right">Next</button>';
//save options
        this.back = this.options.back;
        this.next = this.options.next;
    },
//buttons event
    onBack : function(e) {
        e.preventDefault();
        app.navigate(this.back, {trigger: true});
    },
    onNext : function(e) {
        e.preventDefault();
        app.navigate(this.next, {trigger: true});
    },
//render
    render: function() {
        this.$el.html("");
        this.$el.append(this.backDiv);
        this.$el.append(this.nextDiv);
        return this;
    }
    });

//create router class
    var AppRouter = Backbone.Router.extend({
    routes: {
        "" : 'home',
        ":id" : 'test'
    },
//create different views
   initialize:function () {        
        this.homeView = new NavigateBar({
//pass options to view
            back: "1",
            next: "2"
        });
        this.testView = new NavigateBar({
            back: "3",
            next: ""
        });
    },
//route actions
    home : function() {
        $('#view-goes-here').html(this.homeView.render().el);
    },
    test : function(e) {
        $('#view-goes-here').html(this.testView.render().el);
    }
});

//create app
$(function(){  
    app = new AppRouter();
    Backbone.history.start();
});
​

演示:http://jsfiddle.net/3Jaru/3/,点击下一步按钮两次,你会看到

4

1 回答 1

1

您正在保持对视图的引用,这导致了麻烦,因此当 jQuery 尝试重新绑定事件时它不会这样做。作为一般规则,我永远不会在初始化方法中定义对视图的引用,总是在它之外,这样我可以确保当父方法请求视图的新实例时它被覆盖。

home: function () {
    view = new NavigateBar({
        back: "1",
        next: "2"
    });
    $('#view-goes-here').html(view.render().el);
    // and if you really want to be able to reference it
    this.homeView = view;
},
test: function (e) {
    view = new NavigateBar({
        back: "3",
        next: ""
    });
    $('#view-goes-here').html(view.render().el);
    // and if you really want to be able to reference it
    this.homeView = view;
}

更好的方法是始终确保如果定义了视图,则将其销毁,以便

home: function () {
    /* create a method on the NavigateBar view to clear anything 
     * that needs clearing, such as model binds or funky events
     */
    this.homeView && this.homeview.destroy(); 
    view = new NavigateBar({
        back: "1",
        next: "2"
    });
    $('#view-goes-here').html(view.render().el);
    this.homeView = view;
},
于 2012-05-21T13:42:42.300 回答