0
下面的代碼不正是我想要它做的:事件監聽器和自定義事件的ExtJS
Ext.define('Animal',
{
extend: 'Ext.util.Observable',
name: 'Unknown',
sound: 'Unknown',
constructor: function(name)
{
this.name = name;
this.addEvents('talk'); //not needed. AddListener(.on) creates the event in the Observable if it didn't already exist... - Animal www.sencha.com
this.listeners = this.listeners;
this.callParent(arguments);
for(i = 0; i<arguments.length; i++)//callParent(arguments)? array(ish)
console.log(arguments[i]);
},
makeSound: function()
{
alert(this.name + " says " + this.sound);
this.fireEvent('talk');
},
listen: function()
{
alert(this.name + " is listening.");
}
});
Ext.define('Cats',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Meow',
});
Ext.define('Dogs',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Woof',
});
var cat1 = Ext.create('Cats', 'Domino');
var cat2 = Ext.create('Cats', 'Tiger');
var dog1 = Ext.create('Dogs', 'Bruno');
var dog2 = Ext.create('Dogs', 'Spot');
cat1.on('talk', function(){dog1.listen()});
dog2.on('talk', function(){cat2.listen()});
cat1.makeSound();
cat2.makeSound();
dog1.makeSound();
dog2.makeSound();
DOG1(布魯諾)將監聽cat1.makeSound與dog1.listen迴應。 接下來我想用監聽器的配置嘗試:
var cat1 = new Cats({
name: 'Domino',
listeners:
{
scope: dog1,
talk: dog1.listen
}
});
我似乎有麻煩得到它的工作。不知道我是否正確使用語法,無法找到語法的示例。讓我知道如果你有一個例子或一些信息,可以幫助我解決這個問題。下面是完整的代碼,我對事件處理的監聽器的配置方式:
Ext.define('Animal',
{
extend: 'Ext.util.Observable',
name: 'Unknown',
sound: 'Unknown',
constructor: function(config)
{
this.name = config.name;
this.addEvents('talk'); //not needed. AddListener(.on) creates the event in the Observable if it didn't already exist... - Animal www.sencha.com
this.listeners = this.listeners;
this.callParent(arguments);
for(i = 0; i<arguments.length; i++)//callParent(arguments)? array(ish)
console.log(arguments[i]);
},
makeSound: function()
{
alert(this.name + " says " + this.sound);
this.fireEvent('talk');
},
listen: function()
{
alert(this.name + " is listening.");
}
});
Ext.define('Cats',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Meow',
});
Ext.define('Dogs',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Woof',
});
var cat1 = new Cats(
{
name: 'Domino',
listeners:
{
talk: dog1.listen
}
});
var cat2 = Ext.create('Cats', 'Tiger');
var dog1 = Ext.create('Dogs', 'Bruno');
var dog2 = new Dogs(
{
name: 'Spot',
listeners:
{
talk: cat2.listen
}
});
cat1.makeSound();
cat2.makeSound();
dog1.makeSound();
dog2.makeSound();
「從另一個對象直接調用一個對象方法實在是個壞主意。」 - 沙。 你指的是聽衆配置?如果這樣很好,我只是想以其他方式來以類似的方式完成任務。 你能詳細說明爲什麼我不應該直接從另一個對象調用方法嗎? – FailedFace
您的cat1對象不應該知道您的dog1對象的實現細節。在你的代碼中,cat1對象方法直接調用dog1方法。 Dog1可以訂閱來自cat1的事件,並在處理程序中執行自己的功能。 – sha
啊,好的。謝謝。你說服我重新考慮我的問題,所以我會認爲你的答案是最好的答案。 – FailedFace