简体   繁体   中英

how to attach event to <body> using backbone.js?

Is it possible? Something like this:

...
events {
  'keydown body' : 'doSmth'
}
...

This is not possible because Backbone uses the events hash to subscribe to events on the view's element (view.el property) and the element's descendants. It does not subscribe to events from elements outside the view's element.

So if your view's element is table, then the doSomething() function will be called when the keydown event is fired on the table, but it will not be called if the keydown event is fired on another element on the page.

Generally speaking keydown on 'html' should work, see this question:

keydown on body?

However, it is generally better to have events in a Backbone View be triggered by elements in the View's el. In that case you could make your general app-wide View accept keydown inputs:

events: {
    'keydown': 'doSomething'
}

Simply bind it using a framework such as jQuery inside the initialize method of the view.

 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 unbind, it's important; you can check in keyPress to see if the view still is in the dom (document) by 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM