I am having big trouble fixing this error.
I have a view in Backbone.js and I want to bind some actions on it with keyboard events.
Here is my view :
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;
}
}
});
When I press the keyboard, I get this error :
Uncaught TypeError: Object [object Object] has no method 'apply'
that is triggered by jQuery.
After reading this : Uncaught TypeError: Object [object Object] has no method 'apply'
I also tried :
$(document).on('keydown', function(e) {
this.keyboard(e);
}, this);
but it still gives me the same error.
And :
$(document).on('keydown', 'keyboard', this);
in the events : { 'event' : 'action' } style
but it doesn’t do anything.
I could probably find some hack by using jQuery only somewhere else in my code, but since I am not expert in event handling and Backbone, I want to run it the nice way.
I hope I’m clear, thanks
@roatin-marth was right. The “on” function that was applying wasn’t the backbone one as I expected, which allows to pass the context as a parameter :
$(document).on('keydown', this.keyboard, this);Since it’s a jQuery selector, it’s the jQuery on that applies. Hence I need a proxy to link with context:
$(document).on('keydown',$.proxy(this.keyboard,this));All good, thanks for the help.