gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:04:22 25 4
gpt4 key购买 nike

我有 2 个 Controller :

$.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 Controller 中时,我想注意到 App.Browse Controller 正在做一些事情。

最佳答案

您可以尝试以下方法:

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);
};
})();

在 map Controller 中:

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

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

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

关于JavascriptMVC:在包装 Controller 中监听实例化 Controller 的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12835013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com