以下代码完全符合我的要求:
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(Bruno)将监听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();
答案 0 :(得分:1)
直接从另一个对象调用一个对象方法真是个坏主意。你应该考虑重新设计你的逻辑。如果您需要这些类/对象相互通信,您应该使用您在第一个示例中描述的方法,或者您使用全局事件。