Skip to content

Instantly share code, notes, and snippets.

@FokkeZB
Last active August 29, 2015 14:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save FokkeZB/1d4bc721bb703aa361a4 to your computer and use it in GitHub Desktop.
Save FokkeZB/1d4bc721bb703aa361a4 to your computer and use it in GitHub Desktop.
addEventListenerOnce
var win = Ti.UI.createWindow({
backgroundColor: 'white'
});
win.addEventListener('click', function foo(e) { // note the named function expression needed for the second way
// oringal idea by @fukhaos
// http://www.tidev.io/2014/09/10/the-case-against-ti-app-fireevent-2/#comment-13013
e.source.removeEventListener(e.type, arguments.callee);
// better - strict - one by @tonylukasavage
// https://twitter.com/tonylukasavage/status/511887565100949505
e.source.removeEventListener(e.type, foo);
alert('I will only fire once!');
});
win.open();
@jasonkneen
Copy link

Aren't you missing the event type here?

addEventListener("open", ...

@jasonkneen
Copy link

I've typically used this, which does the same thing effectively:

win.addEventListener("open", foo = function() {
   win.removeEventListener("open", foo);
});

@jasonkneen
Copy link

Also did this in a baseController in Alloy for once firing triggers:

exports.once = function(trigger, callback) {
    $.on(trigger, on = function(e) {
        $.off(trigger, on);
        callback(e);
    });
};

which was handy way to make it reusable in controllers

@FokkeZB
Copy link
Author

FokkeZB commented Sep 16, 2014

@jasonkneen thx for the fix

The second one looks similar too Tony's. However, I like his more. Yours might be confusing as to in which scope the function variable is created don't you agree?

Nice one on the one. I hope Alloy will update BB soon so we have the new event API's including once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment