Search code examples
javascriptbackbone.js

How can I detect window events using Backbone-Views?


Here is my firs try. I'm just trying to detect keyup and keydown events on the window. This worked when I used addEventListener, but I'm moving to a jQuery/Backbone framework.

Here it the module in question. I've verified that the event callbacks are not firing.

var UserTryView = Backbone.View.extend({
    Name: 'UserTry',
    keys: {},
    events: {
        "keyup window"                   : "keyup",
        "keydown window"                 : "keydown"
    },
    keydown: function (e) {
        console.log('keydown detected');
        var self = this;
        this.keys[e.keyCode] = null;
        $A.testKeys(this.keys, '1684', function () {
            self.render();
        });
    },
    keyup: function (e) {
        delete this.keys[e.keyCode];
    },
    render: function () {
        new FavoritesView({el: $A.el('#mm')});
        new FeedView({el: $A.el('#at_view')});
        new AccountView();
        // Storage.setObj(packet.server.smalls);
        Page.flip('main');
    }
});
var user_try_view = new UserTryView();

Solution

  • The events hash will only look at the element itself or child elements. This is inline with the architecture of Views - you generally avoid looking up your tree of views (if you are using the concept of subviews which I hope you are/will).

    For listening to a window event you should hook into it in the normal jQuery way, i.e.:

    initialize: function() {
        _.bindAll(this, 'onWindowKeyUp', 'onWindowKeyDown');
        $(window).on({
            'keyup': this.onWindowKeyUp,
            'keydown': this.onWindowKeyDown
        });
    },
    
    onWindowKeyUp: function(ev) {
        console.log('Key up:', ev)
    },
    
    onWindowKeyDown: function(ev) {
        console.log('Key down:', ev)
    }
    

    Note the _.bindAll. This is optional but it means that within those event callbacks this refers to the view which is generally more useful than the context jQuery gives you.

    P.S. Remember to remove the event when your view is destroyed to prevent memory leaks.