I recently found that in the context of Class, .fireEvent() accepts a 3-rd argument, delay. Firing deferred events can be useful but you need to understand the full difference between the patterns available at your disposal.
Pattern one. It relies on delay creating a function and passing arguments to that function at the time of invocation. Does not actually fire until time is due, but the arguments will be saved during invocation (unless they are objects, therefore by reference).
var a = new Class({ Implements: [Events], initialize: function() { this.foo = 1; this.fireEvent.delay(1000, this, ['event', [this.foo, 'moar']]); // won't actually fire until time is due. this.addEvent('event', function() { console.log(arguments, this); }); this.foo = 2; } }); new a();
In pattern #2, we use the delayed event provided by MooTools. The key thing here is that the event actually fires
at the time of invocation but does not arrive until the due time. The problem is, ‘just-in-time’ adding of the event after won’t work as there is no event handler prior to calling .fireEvent. In this example, nothing will log – but you can add your event before firing. Arguments will be the same as at the of invocation.
var b = new Class({ Implements: [Events], initialize: function() { this.foo = 1; this.fireEvent('event', [this.foo, 'moar'], 1000); // has already fired, so adding the event handler now is pointless this.addEvent('event', function() { console.log(arguments, this); }); this.foo = 2; } }); new b();
In pattern 3, we wrap things into an anonymous function that is deferred for later via setTimeout (well, Function.delay() which is the same thing). The bonus to this pattern is that it will dispatch the value at the time of firing, not at the time of deferral.
var c = new Class({ Implements: [Events], initialize: function() { this.foo = 1; (function() { this.fireEvent('event', [this.foo, 'moar']); }).delay(1000, this); // only pattern that uses fresh enough data this.addEvent('event', function() { console.log(arguments, this); }); this.foo = 2; } }); new c();
Hope this gives you something to take away in your app development. Look at the jsfiddle and your console here: http://jsfiddle.net/dimitar/mTkvE/
GitHub flavoured markdown enabled.