javascriptjqueryjquery-eventsjavascriptmvc

JavascriptMVC: Listen to event of instantiated Controller in wrapper Controller


I have 2 controllers:

$.Controller('App.Browse',
/** @Static */
{
    defaults : {}
},
/** @Prototype */
{
    init : function(){
        $('#map').app_map();
    },
    // how can I listen here for an event of app_map() controller
})

and

$.Controller('App.Map',
/** @Static */
{
    defaults : {}
},
/** @Prototype */
{
    init : function(){
        // how can I trigger an event to be listened by app_browser() controller
    },
})

The short idea is that while I'm in the App.Map controller I would like to notice the App.Browse controller to do something.


Solution

  • JMVC is prepared for that. Just declare it like this:

    $.Controller('App.Browse',
    /** @Static */
    {
        defaults : {
            mapController: null
        },
        listensTo: ['mapCustomEvent']
    },
    /** @Prototype */
    {
        init : function(){
            $('#map').app_map();
        },
    
        '{mapController} mapCustomEvent': function(element, event, param) {
            //handle event
        }
    })
    
    $.Controller('App.Map',
    /** @Static */
    {
        defaults : {}
    },
    /** @Prototype */
    {
        init : function(){
            param = "something I'd like to pass into event listener";
            $(this).trigger('mapCustomEvent', params);
        }
    })
    

    And instantiate:

    map = new App.Map('#map');
    new App.Browse($('#browse'), {mapController: map});