JavaScript 中介器模式;组件名称未定义
JavaScript Mediator pattern; Component name is undefined
在中介模式的以下实现中,为什么初始化方法中的 this.name 总是未定义?正如我期望它是测试对象一样。我怎样才能做到这一点?
另外,如何创建测试对象的新实例?
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');
这是因为在函数块中,你要返回,this
表示块本身,而不是中介器对象(你可以尝试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
相关文章:
- 组件生命周期问题/无法处理未定义的问题
- GoogleMap JSX组件中未定义的变量
- Ember服务在注入组件并在计算属性中使用后是未定义的
- ReactJS中未定义组件
- 使用AMD时未定义淘汰组件视图模型
- 传递给Angular2组件的字符串始终未定义
- 尝试在组件之间传递数据时未定义
- 未定义编码 URI 组件
- 角度2 - 未定义组件
- Vue.js 使用 Vuex 和自定义组件,@click方法输出未定义
- JavaScript 中介器模式;组件名称未定义
- 嵌入 API 自定义组件:未捕获类型错误:无法读取未定义的属性“ViewSelector2”
- 将控制器操作传递给EmberJS中的组件会返回未定义的结果
- 反应:“this”在组件函数中是未定义的
- Ember”;这个“;组件中未定义
- 在递归聚合物组件中插入新子组件时,无法读取未定义的属性“concat”
- 组件对话框无法在IE中运行(无法获取属性'clear'未定义或空引用)
- ReactJS: '类型未定义'加载组件时
- React组件方法this.state.myState从child返回后未定义
- React Redux - 不能使用将组件的方法传递给子组件 - 未定义的错误