创作者类生成他的孩子。如果单击Child,调用ClickedOnMyChild of Creator的最佳方法是什么?
function Creator()
{
var c1 = new Child("Albert");
var c2 = new Child("Sarah");
var ClickedOnMyChild = function()
{
//alert name of child
}
}
function Child(name)
{
this.name = name;
function ClickHandler()
{
// a click on me, better call my Creator
}
}
到目前为止我的想法:
答案 0 :(得分:2)
选项编号3. is indeed a good practice
。如果你曾经编写过某些东西,你需要保持层次结构,你就会明白它有多棒。您可以将您的子类更改为此,并通过调用Creator
方法在setCreator
类中明确设置创建者:
function Child(name)
{
this.name = name;
this.creator = null ;
this.setCreator = function(creator){
this.creator = creator ;
}
this.clickHandler = function()
{
if (this.creator)
this.creator.clickedOnMyChild();
}
}
注意:
this
个关键字。否则你将无法在课外使用它们。答案 1 :(得分:2)
我会选择第二个:在Child中触发自定义事件。因为它不仅允许您在父母中处理事件,而且还any objects
对事件感兴趣。
以下是示例代码:
function Event(sender) {
this._sender = sender;
this._listeners = [];
}
Event.prototype = {
attach: function (listener) {
this._listeners.push(listener);
},
notify: function (args) {
for (var i = 0; i < this._listeners.length; i++) {
this._listeners[i](this._sender, args);
}
}
};
function Creator()
{
var c1 = new Child("Albert");
var c2 = new Child("Sarah");
c1.click.attach(function (sender,args){
//alert name of child
alert(args);
});
c2.click.attach(function (sender,args){
//alert name of child
alert(args);
});
}
function Child(name)
{
this.name = name;
this.click = new Event(this);
var _this = this;
function ClickHandler()
{
_this.click.notify(_this.name);
}
}
参考链接:http://alexatnet.com/articles/model-view-controller-mvc-javascript