JavascriptMVC:在包装器Controller中监听实例化Controller的事件

时间:2012-10-11 08:10:34

标签: javascript jquery javascript-events javascriptmvc

我有2个控制器:

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

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

简短的想法是,当我在App.Map控制器中时,我想注意App.Browse控制器做某事。

2 个答案:

答案 0 :(得分:2)

你可以尝试这些方法:

window.createEventManager = (function() {

var Event = function(manager, name) {
    this.name = name;
    this._manager = manager;
    this._listeners = [];
};

Event.prototype = {
    listen: function(fn) {
        if (!$.isFunction(fn)) {
            throw "fn is not a function.";
        }

        this._listeners.push(fn);
    },

    fire: function(args) {
        args = args || {};
        args.name = this.name;

        var ls = this._listeners;
        for (var i = 0, l = ls.length; i < l; ++i) {
            ls[i](args);
        }

        this._manager.fire(args);
    }
};


var EventManager = function(eventNames) {
    for (var n in eventNames) {
        this[eventNames[n]] = new Event(this, eventNames[n]);
    }

    this._listeners = [];
};

EventManager.prototype = {
    /**
     * Listen to all events
     * @param fn
     */
    listen: function(fn) {
        if (!$.isFunction(fn)) {
            throw "fn is not a function.";
        }

        this._listeners.push(fn);
    },

    fire: function(args) {
        var ls = this._listeners;
        for (var i = 0, l = ls.length; i < l; ++i) {
            ls[i](args);
        }
    },

    getEvent: function(name){
        return this[name];
    }
};

return function(eventNames) {
    return new EventManager(eventNames);
};
})();
地图控制器中的

init : function(){
    events = createEventManager(["mapTrigger"]);
},

并在浏览器中通过以下方式收听:

  $('#map').app_map().events.getEvent("mapTrigger").listen(function(){
        // Logic to perform on trigger.
  });

答案 1 :(得分:1)

JMVC为此做好了准备。只需声明如下:

$.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);
    }
})

并实例化:

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