Soatl
Soatl

Reputation: 10592

Backbone window keypress event?

I know that I can use the window.keypress event

$(window).keypress(function(e) {
    alert('hello world');
});

But I was wondering if there was a way to use the backbone events to catch a keypress anywhere in the window?

I cannot do it on a view, because my page will contain multiple views.

Upvotes: 2

Views: 384

Answers (2)

Javier Buzzi
Javier Buzzi

Reputation: 6828

This should do the trick:

var OverlordView = Backbone.View.extend({
  events: {
    "keypress": "alert"
  },
  alert: function() {
    alert('hello world')
  }
});

$(function() {
    new OverlordView({el: $('body')[0]})
})

Demo: http://jsfiddle.net/3obw5k8j/

Upvotes: 2

Anakin
Anakin

Reputation: 3120

Backbone's event handlers only works in its own view. Doesnt affect window context. You need to setup inside initialize i assume.

var MyView = Backbone.View.extend({
    initialize : function(){
        $(window).on("keypress", this.windowKeyPress)
    },
    windowKeyPress : function(){
        // handler.
    }
});

Upvotes: 0

Related Questions