2

I have the following code in index.js:

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

on foo.js I have the following:

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

// execute runEvent() somewhere later

However, the function in the event listener does not seem to run.

What am I doing wrong?

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

2 Answers2

4

You are missing a point that custom events can only be added on a controller, not on the view.

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

In this line, you are holding the view by using getView() in win variable.

Now, it should be like this:

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 will remain same:

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

// execute runEvent() somewhere later
Prashant Saini
  • 3,539
  • 1
  • 10
  • 24
0

In my case, i was using

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

I've been smacking my head for the last hour...

on top of what @PrashantSaini presented, there s no addEventListener on controller objects, controllers have the on function, so it should be :

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

update

My answer is a heads up for the fact that there no addeventlistener on controller object.

TheFuquan
  • 1,737
  • 16
  • 18