钛 addeventlistener 到函数调用

bha*_*ral 2 event-listener titanium

在 appcelerator 钛中,是否可以在函数调用中使用事件侦听器?

有点像

var coolManDool = function(){...};
coolManDool.addEventListener('what goes here?", function(){ ... } );
Run Code Online (Sandbox Code Playgroud)

我希望能够以这种方式包装特定的一组函数,以确保它们执行某些操作。未来的代码可能会扩展做某事,在我的代码中有一个中心位置来控制它会非常好。

Ana*_*and 5

您不能将 eventListener 添加到任何函数,但您可以在您的函数内触发一个事件,也可以将您的函数用作事件的回调。事件侦听器用于处理事件。在您的情况下,如果您想向函数添加事件,您可以简单地在 Titanium 中创建自定义事件。例如,如果您想在调用函数时执行某些特定操作,您可以简单地按如下方式进行。

//Creating the custom event
window.addEventListener('myEvent', function(){
    alert('function called')
});

function foo(){
    //Some actions
    window.fireEvent('myEvent');
}
Run Code Online (Sandbox Code Playgroud)

您还可以向应用程序本身添加事件(应用程序级事件)。应用级事件对您的应用来说是全局的。它们可以在所有上下文、功能范围、CommonJS 模块等中访问。您可以触发它们并通过 Ti.App 模块监听它们。

Ti.App.addEventListener('myAppEvent', function(){
    alert('Application level event get fired');
});
//Fire the event like
Ti.App.fireEvent('myAppEvent');
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Titanium 中的事件处理