【发布时间】:2017-06-21 11:25:22
【问题描述】:
有什么方法可以覆盖 Titanium 中 Widget 元素的点击事件监听器?
我有一个小部件,并且在我使用该小部件的控制器中,我需要在单击元素时执行一些其他操作,而不是在小部件中定义的操作。
有什么方法可以实现吗?
TIA :)
【问题讨论】:
标签: javascript titanium appcelerator appcelerator-titanium
有什么方法可以覆盖 Titanium 中 Widget 元素的点击事件监听器?
我有一个小部件,并且在我使用该小部件的控制器中,我需要在单击元素时执行一些其他操作,而不是在小部件中定义的操作。
有什么方法可以实现吗?
TIA :)
【问题讨论】:
标签: javascript titanium appcelerator appcelerator-titanium
是的,当然你可以覆盖任何你想要的东西。
使用 Alloy,您将通过 id 参数访问小部件,而使用经典模型,您将只需使用小部件变量名称。
假设,您的 XML 文件中有一个 com.widget.somewidget 小部件:
index.xml
<Alloy>
<Window>
<Widget id="widget_id" src="com.widget.somewidget"></Widget>
</Window>
</Alloy>
widget.xml
<Alloy>
<Button id="widget_button" title="Hello World!" />
</Alloy>
在 widget.js 中,您现在将导入要覆盖点击事件的元素,如下所示:
$.exportedButtonId = $.widget_button;
最后,您可以像这样覆盖按钮点击事件:
index.js
var widgetButton = $.widget_id.exportedButtonId;
widgetButton.addEventListener('click', function (e){});
这是如何更灵活地利用小部件的非常基本的示例,但实现是无穷无尽的,并且取决于应用程序的需求。所以祝你好运!
【讨论】:
要覆盖给定的函数,我会在小部件中导出一个 setter 函数:
像往常一样构建小部件 widget.xml:
<Alloy>
<Button onClick="doClick" title="Hello World!" />
</Alloy>
导出一个 setter 函数 $.overrideListener 以便能够从小部件外部覆盖 clickHandler
widget.js:
function doDefaultStuff(e){
//Do default stuff
}
var clickHandler = doDefaultStuff
function doClick(e){
clickHandler(e)
}
$.overrideListener = function(callback){
clickHandler = callback
}
index.xml:
<Alloy>
<Window>
<Widget id="widget_id" src="com.widget.somewidget"></Widget>
</Window>
</Alloy>
如果您希望执行与默认行为不同的操作,请覆盖 clickHandler
index.js:
function doCustomStuff(e){
//Do Custom Stuff
}
$.widget_id.overrideListener(doCustomStuff)
【讨论】: