我已经创建了一个自定义组件,更方便地作为SkinnablePopUpContainer使用,并且我想使用相同的函数来调用和接收UI中几个按钮的数据。无需为每个按钮创建新功能,实现此目的的最佳方法是什么?如何在多个组件中重用单个功能?
<fx:Script>
<![CDATA[
import spark.events.PopUpEvent;
protected function button1_clickHandler(event:MouseEvent):void
{
popup.addEventListener(PopUpEvent.CLOSE, onPopUpEventClose1, false, 0, true);
popup.open(this);
}
private function onPopUpEventClose1(event:PopUpEvent):void {
popup.removeEventListener(PopUpEvent.CLOSE, onPopUpEventClose1);
trace(event.commit);
trace(event.data);
button1.label=event.data;
}
protected function button2_clickHandler(event:MouseEvent):void
{
popup.addEventListener(PopUpEvent.CLOSE, onPopUpEventClose2, false, 0, true);
popup.open(this);
}
private function onPopUpEventClose2(event:PopUpEvent):void {
popup.removeEventListener(PopUpEvent.CLOSE, onPopUpEventClose2);
trace(event.commit);
trace(event.data);
button2.label=event.data;
}
]]>
</fx:Script>
<s:Button id="button1" x="102" y="103" label="Button 1 Numbers"
click="button1_clickHandler(event)"/>
<s:Button id="button2" x="102" y="200" label="Button 2 Numbers"
click="button2_clickHandler(event)"/>
你可以看到我宁愿有一组函数可以处理所有这些,而不是手动编码每个函数。
有没有办法获得调用该函数的组件的ID?解决这个问题的最好方法是什么?
编辑:解
我已经能够代替所有的修剪器,其代码如下:
private var buttonPick:Button;
public function button_clickHandler(button:Button):void
{
switch (button) {
case button1: popup.addEventListener(PopUpEvent.CLOSE, onPopUpEventClose, false, 0, true);
popup.open(button);
break;
case button2: popup.addEventListener(PopUpEvent.CLOSE, onPopUpEventClose, false, 0, true);
popup.open(button); break;
}
buttonPick = button;
}
private function onPopUpEventClose(event:PopUpEvent):void {
popup.removeEventListener(PopUpEvent.CLOSE, onPopUpEventClose);
trace(event.commit);
trace(event.data);
buttonPick.label=event.data;
}
,并以此为MXML:
<s:HGroup click="button_clickHandler(event.target as Button)">
<s:Button id="button1" x="102" y="103" label="Button 1 Numbers"
/>
<s:Button id="button2" x="102" y="200" label="Button 2 Numbers"
/>
</s:HGroup>
感谢意见和建议!如果有更有效的方法来做到这一点比案例陈述,一定要建议!
感谢您输入@RIAstar,我刚刚读到了NoobsArePeople2的文章链接,它涉及到您提出的一些问题:所以我尝试了一下,然后我意识到,我必须为每个按钮使用一个案例?对于少数这可能是好的,但如果我有像30个按钮的东西,这仍然是最有效的路线? – SQLiteNoob
来提一提,我看到你在说什么,但我遇到了一些麻烦: 按钮点击调用弹出窗口,然后我必须听PopUpEvent.CLOSE事件以从弹出窗口中检索数据 - 如果我可以通过哪个按钮做buttonclick函数点击onPopUpEventClose我会解决。 – SQLiteNoob
@SQLiteNoob由于您在两个按钮上执行完全相同的操作,因此您甚至不再需要该开关。只是'如果(按钮){popup.addEventListener(PopUpEvent.CLOSE,onPopUpEventClose); popup.open(按钮); ''会做得很好。 – RIAstar