2

我在index.js下面的代码:钛/合金:事件侦听器添加到窗口

var win = Alloy.createController('foo').getView(); 
win.open(); 
win.addEventListener('exampleEvent', function() { 
    Ti.API.info('Event Run!'); // does not seem to run 
}); 

foo.js我有以下几点:

function runEvent() { 
    $.trigger('exampleEvent'); 
    $.getView().close(); 
} 

// execute runEvent() somewhere later 

但是,事件侦听器中的函数似乎不运行。

我在做什么错?

回答

3

您错过了一个观点,即自定义事件只能添加到控制器上,而不能添加到视图上。

var win = Alloy.createController('foo').getView(); 

在该行中,您通过使用getView()赢得变量保持的视图。

现在,它应该是这样的:

var win = Alloy.createController('foo'); 

win.on('exampleEvent', function() { 
    Ti.API.info('Event Run!'); // it will run now as you have added custom event on controller (means $ in .js file) itself. 
}); 

// now you can get the top-most view (which is a window in this case) and can further use open() method on window 
win.getView().open(); 

foo.js将保持不变:

function runEvent() { 
    $.trigger('exampleEvent'); 
    $.getView().close(); 
} 

// execute runEvent() somewhere later 
0

就我而言,我是使用

var controller = Alloy.createController('myController'); 
controller.addEventListener("customEvent",function(){}); 

我一直嫌我的头了一个小时......

在什么@PrashantSaini呈现顶部,有S于控制器对象没有的addEventListener,控制器具有on功能,所以它应该是:

controller.on("customEvent",function(){}); 

更新

我的回答是一个抬头的事实,有控制器对象上没有的addEventListener。

+0

我不明白这与@Prashant Sainj有什么不同回答 –

+0

检查更新 – TheFuquan