How to bind an event with <body> using backbone.js?
This is not possible because Backbone uses an event hash to subscribe to events in the view element (view.el property) and descendants of the element. It does not subscribe to events from elements outside the presentation element.
So, if your view element is a table, then the doSomething () function is called when the keydown event is fired in the table, but it will not be called if the keydown event is fired on another element on the page.
In general, keydown on 'html' should work, see this question:
However, as a rule, it is best that events in Backbone View mode are triggered by elements in the View el element. In this case, you can share the View application to log in to the system:
events: { 'keydown': 'doSomething' } Just bind it using a framework like jQuery inside the view initialization method.
var View = Backbone.View.extend({ initialize: function() { _.bindAll(this, "keyPress"); $(document).bind('keydown', this.keyPress); }, keyPress: function(e) { console.log(e.keyCode); alert(e.keyCode); return false; } }); Do not forget to untie, this is important; you can check keyPress to see if the view is still in dom (document) using $(document).find(this.$el).size()
if($(document).find($(this.options.container)).size() <= 0) { alert("view not in document"); $(document).unbind('keydown', this.keyPress); }else { alert("view is here"); }