Mojo.Function.Synchronize

Class Detail

Instances of this class are used to ensure a set of callback functions are all called at the same time. After creating, use the wrap() method to wrap any callbacks you wish to synchronize before passing them to an asynchronous service. The synchronize object will defer calling any of them until all of the returned wrappers have been called.

Example Use

Mojo generally uses the syncCallback option to defer some processing until a variety of other tasks have all completed. For example, the completion function passed to a scene assistant's aboutToActivate() method is actually an "empty" wrapper function from a Synchronize object. It's used as a trigger to continue the scene transition.

One could implement this use case like so:

var synchronizer = new Mojo.Function.Synchronize({
  syncCallback: this.continueSceneTransition()});
var doNothing = function() {};
var otherWrapper = synchronizer.wrap(doNothing);

curScene.aboutToActivate(synchronizer.wrap(doNothing));
beginOtherOperation(otherWrapper); 

When both wrappers have been called, this.continueSceneTransition() will be called and the scene transition will continue.

Alternate Use

An alternative use of Synchronize is to make sure that a function is called within a certain amount of time, and that it's not called more than once. This works by specifying a timeout for the Synchronize object, and again using the syncCallback.

var synchronizer = new Mojo.Function.Synchronize({
  syncCallback: this.thingComplete(),
  timeout: 3});

beginThing(synchronizer.wrap(function() {}));

Here we wrap an empty function, which just acts as a trigger for calling this.thingComplete(). If the wrapper is not called within 3 seconds, then thingComplete() will be called anyway...and any subsequent calls to the wrapper will have no affect.

Parameters

  • {object} inOptions

    inOptions may include the following properties:

    • syncCallback: Function - If provided, it will be called after all the callbacks have been dispatched. It receives a boolean argument which is 'true' if the synchronizer timed out.

    • timeout: number - If provided, the synchronizer will stop waiting after this number of seconds. All "received" wrapped functions and the syncCallback function will be called. Any wrappers created by this synchronizer that have not yet been called will be ignored; however, subsequent calls to them will immediately pass through to the wrapped function.

Method Summary

  • wrap(callback)

Method Detail

{Function} wrap(callback)

Wrap and record a function object such that it will not be called until all similarly wrapped callbacks have been invoked.

Parameters

  • {Function} callback - The callback function that should be synchronized.

Returns

A wrapper function suitable for passing in place of the callback.