Search code examples
javascriptbackbone.js

Backbone - listenTo multiple events and determine which event is fired


I would like to register one listener for two events and determine which event is fired.

// how do I determine which event fired?
this.listenTo( Backbone, 'minimize maximize', function( data ){ 
    console.log( 'minimize or maximize called, but which one?' );
    /*
    if( minimize )
        doStuff();
    if( maximize )
        doOtherStuff();
    */
});

I know this could be separated into two listeners:

this.listenTo( Backbone, 'minimize', callbackOne);
this.listenTo( Backbone, 'maximize', callbackTwo);

But I would like to know if the first way is possible?


Solution

  • One way to do this is to use the magic "all" event to handle all events and then discriminate based on the event name:

    this.listenTo( Backbone, 'all', function(event_name, data ){ 
    
        if( event_name == "minimize" )
            doStuff();
        if( event_name == "maximize" )
            doOtherStuff();
    });
    

    Of course, this is not optimal because this will be triggered on all events, which adds unneccessary overhead to your application.

    However, perhaps you find it nicer to use the map syntax like so:

    function handlerForMaximize(data){
        // Do something useful here
    }
    function handlerForMinimize(data){
        // Do something useful here
    }
    
    this.listenTo( Backbone, {
        "maximize" : handlerForMaximize,
        "minimize" : handlerForMinimize
    });
    

    If you insist in using a single function for everything, you can do this (requires underscore.js):

    function myHandler(event_name, data){
        if(event_name == "maximize"){
            // Do something useful
        }
        if(event_name == "mimimize"){
            // Do something useful
        }
    }
    this.listenTo( Backbone, {
        "maximize" : _.partial(myHandler, "maximize"),
        "minimize" : _.partial(myHandler, "minimize")
    });