0

我在修复这个错误时遇到了很大的麻烦。

我在 Backbone.js 中有一个视图,我想将一些操作与键盘事件绑定。

这是我的观点:

window.PicturesView = Backbone.View.extend({
    initialize : function() {
        $(document).on('keydown', this.keyboard, this);
    },
    remove : function() {
        $(document).off('keydown', this.keyboard, this);
    },
    render : function(eventName) {
        // blah blah blah
    },
    next : function() {
        // blah
    },
    prev : function() {
        // blah
    },
    keyboard : function(e) {
        console.log(e.keyCode);
        if (e.keyCode == 37) {
            this.prev();
            return false;
        }
        if (e.keyCode == 39) {
            this.next();
            return false;
        }
    }
});

当我按下键盘时,我得到这个错误: Uncaught TypeError: Object [object Object] has no method 'apply' 这是由 jQuery 触发的。

读完后:未捕获的类型错误:对象 [对象对象] 没有方法“应用”

我也试过: $(document).on('keydown', function(e) { this.keyboard(e); }, this); 但它仍然给我同样的错误。

并且: $(document).on('keydown', 'keyboard', this);events : { 'event' : 'action' }风格上,但它没有做任何事情。

我可能只在代码中的其他地方使用 jQuery 来发现一些 hack,但是由于我不是事件处理和 Backbone 方面的专家,所以我想以一种好的方式运行它。

我希望我清楚,谢谢

4

2 回答 2

1

@roatin-marth 是对的。正在应用的“on”函数不是我预期的主干函数,它允许将上下文作为参数传递: $(document).on('keydown', this.keyboard, this);

因为它是一个 jQuery 选择器,所以它适用于 jQuery。因此我需要一个代理来链接上下文: $(document).on('keydown',$.proxy(this.keyboard,this));

一切都好,感谢您的帮助。

于 2012-11-14T13:16:37.367 回答
-1

Backbone 的典型事件语法应该可以工作。摆脱初始化代码并尝试它。

// code above unaltered
initialize : function() { }, // of course you can remove these two, it was just to clarify that they should be empty.

remove : function() { },

render : function(eventName) {
    // blah blah blah
    this.delegateEvents(); // just to have them re-bound if the view is removed
},

events: {
    'keydown': 'keyboard'
}
// rest of the code unaltered
于 2012-10-30T17:25:44.610 回答