我的总体目标是让指定的动物(cat1)发出声音(警报框)并让另一只特定的动物(dog1)听猫发出声音并用它的声音回复。
在下面的代码中,我尝试使用 bind 命令来实现我的回调。
Ext.define('Animal',
{
name: 'Unknown',
sound: 'Unknown',
listening: this.listening,
constructor: function(name)
{
if (name)
{
this.name = name;
}
},
makeSound: function()
{
alert(this.name + " says " + this.sound);
if(this.listening)
{
this.listening();
}
},
isListening: function(listening)
{
this.listening = listening;
}
});
Ext.define('Cats',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Meow',
listening: this.listening,
listen: function()
{
if(this.listening)
alert(this.name + "is listening.");
}
});
Ext.define('Dogs',
{
extend: 'Animal',
name: 'Unknown',
sound: 'Woof',
listening: this.listening,
listen: function()
{
if(this.listening)
alert(this.name + "is listening.");
}
});
var cat1 = Ext.create('Cats', 'Domino');
var cat2 = Ext.create('Cats', 'Tiger');
var dog1 = Ext.create('Dogs', 'Bruno');
var dog2 = Ext.create('Dogs', 'Spot');
dog1.listen = dog1.listen.bind(dog1); //failed miserably, not sure of the proper usage,
cat1.isListening(dog1.listen); //I saw an example using this format.
cat1.makeSound();
cat2.makeSound();
dog1.makeSound();
dog2.makeSound();
这当然对我不起作用,但它可能就像绑定命令的错误使用一样简单(控制台中没有错误有时很难说)我真正想要完成的方法如下:(评论在下面的代码中解释得很好)
Ext.define('Animal',
{
name: 'Unknown',
sound: 'Unknown',
listening: this.listening,
constructor: function(name)
{
if (name)
{
this.name = name;
}
},
makeSound: function()
{
alert(this.name + " says " + this.sound);
},
listen: function(obj)
{
if(this.listening)
alert(obj.name + " is listening to " + this.name + ".");
}
});
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');
//some callback that will wait for a specific animal to make a sound
//and call the listen function in an intelligent way so I get this.name
//to be the animal that made that sound and the obj.name to be the
//animal that is listening
cat1.makeSound();
cat2.makeSound();
dog1.makeSound();
dog2.makeSound();
这需要我使用正确的范围,当然我不知道如何处理。主要是我希望在这方面得到一些帮助,同时远离回调的自定义事件。任何帮助表示赞赏。