在下面的中介者模式的实现中,为什么初始化方法中的this.name总是undefined?正如我所期望的那样,它是 TestObject。我怎样才能做到这一点?
另外,如何创建 TestObject 的新实例?
Mediator = function() {
var debug = function() {
// console.log or air.trace as desired
};
var components = {};
var broadcast = function(event, args, source) {
var e = event || false;
var a = args || [];
if (!e) {
return;
}
//debug(["Mediator received", e, a].join(' '));
for (var c in components) {
if (typeof components[c]["on" + e] == "function") {
try {
//debug("Mediator calling " + e + " on " + c);
var s = source || components[c];
components[c]["on" + e].apply(s, a);
} catch (err) {
debug(["Mediator error.", e, a, s, err].join(' '));
}
}
}
};
var addComponent = function(name, component, replaceDuplicate) {
if (name in components) {
if (replaceDuplicate) {
removeComponent(name);
} else {
throw new Error('Mediator name conflict: ' + name);
}
}
components[name] = component;
};
var removeComponent = function(name) {
if (name in components) {
delete components[name];
}
};
var getComponent = function(name) {
return components[name] || false;
};
var contains = function(name) {
return (name in components);
};
return {
name : "Mediator",
broadcast : broadcast,
add : addComponent,
rem : removeComponent,
get : getComponent,
has : contains
};
}();
// Components
Mediator.add('TestObject', function() {
var someNumber = 0; // sample variable
var someString = 'another sample variable';
return {
onInitialize: function() {
// this.name is automatically assigned by the Mediator
alert(this.name + " initialized.");
},
onFakeEvent: function() {
someNumber++;
alert("Handled " + someNumber + " times!");
},
onSetString: function(str) {
someString = str;
alert('Assigned ' + someString);
}
}
}());
Mediator.broadcast("Initialize");
Mediator.broadcast('FakeEvent');
Mediator.broadcast('SetString', ['test string']);
Mediator.broadcast('FakeEvent');
Mediator.broadcast('SessionStart');
最佳答案
这是因为在您要返回的函数 block 中,this
代表 block 本身,而不是中介对象(您可以尝试 console.log(this);
在 onInitialize
中查看)。
编辑:
要将名称组件添加到您的回调中,您可以这样做
var addComponent = function(varName, component, replaceDuplicate) {
if (varName in components) {
if (replaceDuplicate) {
removeComponent(varName);
} else {
throw new Error('Mediator name conflict: ' + varName);
}
}
components[varName] = component;
components[varName].name = varName;
};
有很多名字,所以我把本地的name
改成了varName
关于JavaScript 中介模式;组件名称未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474219/