Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically extend event from a base view

Tags:

backbone.js

I have a base class for all views and then in each section of the app, like profiles, I also have a base class. That way shared templates and properties can be used throughout my app on many levels.

I know that if you make the event property in a Backbone view a function instead of an object literal, it will be instantiated for you, I'm not sure how to use this to my advantage, though. My question is, what's the best way to automatically extend events created in a base view.

I know one possibility where I, on view initialize, fetch the base event class and extend my current event on to it, but it seems a little hacky, and I would have to duplicate this code on every view. If you know a better way please share.

Thanks.

like image 482
Mauvis Ledford Avatar asked Oct 12 '11 22:10

Mauvis Ledford


2 Answers

var ParentView = Backbone.View.extend({
    'events': {
        'click .parent-something': "onParentSomethingClick"
    }
}); 

var ChildView = ParentView.extend({
    'events': _.extend({
        'click .something': 'onSomethingClick',
    }, ParentView.prototype.events)
});

It's not doing nothing, but it's the simplest way I've seen so far.
I've also created a gist on another way I've been using: https://gist.github.com/1271041

like image 195
Johnny Avatar answered Sep 24 '22 03:09

Johnny


Here's how I extend the parent view's events in my child view:

var ParentView = Backbone.View.extend({

        events: {
            'click .link': 'onLinkClick'
        }
});

var ChildView = ParentView.extend({

        events: function(){
            return _.extend({
                'click .something': 'onSomethingClick',
            }, this.constructor.__super__.events);
        }
});

Note: this only works as of Backbone 0.5.3. Before that version, you couldn't define events as a function.

like image 32
Johnny Oshika Avatar answered Sep 21 '22 03:09

Johnny Oshika