webOShelp.net

Get the latest on:webOS Developers' RSS FeedwebOS Facebook page webOS Twitter Feed

Home Resources API Reference
webOS Mojo API - Contents
Filter Title 
Filter Content 
 
Toggle all descriptions Collapse all descriptions
Miscellaneous top
Article Title
Mojo.loadScriptWithCallback(path, callback, optionalDocument)

Asynchronously load a JavaScript file by adding a script tag to the header of the document.

Parameter Type Description
path String Absolute or relative path to the source file.  If relative it is relative to the current document's location.
callback Function Function called when the script  completes loading or fails to load.
optionalDocument HTMLDocument Document to which to add the script tag.  Defaults to global document.

Mojo.Animation top
Article Title
Mojo.Animation.animateClip(element, side, animationType, details)

This is used to animate the 'clip' style property of DOM elements. Only one side may be animated at a time. Any existing clip animation on the indicated node is cancelled when the new one is applied, and this generally behaves like animateStyle().

In addition, animateStyle() is used to provide underlying functionality, so it's details are generally supported as well.

Argument Type Description
element Object DOM element whose style is to be animated
side String The side of the element to clip from.  top, left, bottom or right
animationType String linear, bezier or zeno.  Determines the change in rate of animation over its duration
details Object Additional animation parameters defined below.  clip property must be defined (see below).  Most ValueAnimator details are also supported.

Details object properties:

Argument Type Description
clip Object Hash of numbers indicating current values for the clipping rectangle.  Required.

Example \usage:

This is used to animate the clipping rectangle for ProgressPill widgets.

clipStyleAnimator = Mojo.Animation.animateClip(
this.progressDiv, 'left', this.oldWidth, width, 0.2,
clip: {
top: 0, left: this.oldWidth, bottom: 12, right: 0
},
curve: 'ease-in-out'
);
Mojo.Animation.animateStyle(element, attr, animationType, details)

Used to animate CSS style properties of DOM elements. Animates the specified attribute to the specified value over a specified duration. Any existing animation on the indicated node for the indicated style attribute is cancelled when the new one is applied. The animator will override any other changes made to the animated attribute while the animation is in progress. Currently, only integer valued attributes are supported, so colors and opacity cannot be animated (except using the styleSetter detail property).

One difference between this animator and CSS transitions is that both a fromValue and a toValue must be specified. This enables the animation speed to be "correct" when an attribute is being animated back and forth between two values and the back animation needs to be started while the forward animation is only partially complete.

Argument Type Description
element Object DOM element whose style is to be animated
attr Object Name of the CSS style attribute to be animated
animationType String linear, bezier or zeno.  Determines the change in rate of animation over its duration.
details Object Additional animation parameters defined below.  Most ValueAnimator details are also supported.

Details object properties:

Property Type Description
currentValue Number Current value of style attribute being animated.  Default is to call parseInt() on the style property.
styleSetter Function Function that actually applies the style change.  Allows for setting complex style properties like clip.
from Number Starting value for number being animated (passed to ValueAnimator)
to Number End value for number being animated (passed to ValueAnimator)
duration Number Duration of the animation in seconds

Example usage:

This code is used to animate spacers to 0 height when doing drag and drop reordering in lists. Note the use of an onComplete function to remove the 0-height spacer from the DOM.

    Mojo.Animation.animateStyle(
this.curDragSpacer, 'height', this.dragHeight, 0, .2,
{
onComplete:function(el){Element.remove(el);}
}
);

animateValue() is used to provide underlying functionality, so its details are generally supported as well.

Mojo.Animation.animateValue(q, animationType, callback, details)

Animates a value between the two specified numbers over the specified duration.  Calls the specified callback function with the current value at each step of the animation. Returns an animation object that can be used to end the animation early.

Methods

Argument Description
cancel() Same as complete() but the callback is never called with the target value.
complete()

Called automatically at completion of animation.  Calls the value callback one last time with the target value and Calls onComplete function if specified and removes the animator from the queue

Parameters

Argument Type Description
q Object Animation queue to use to run the animation.
animationType String Can be linear, bezier, zeno.  Determines the rate of animation throughout its duration
callback Function Called each step of the animation as the value changes.  Argument:  Current value
details Object Object containing additional properties (optional)

Properties for details object:

Argument Type Description
onComplete Function Function called when animation is complete.  Arguments include animated element and boolean canclled value.
reverse Boolean True causes animation to run in reverse.
curve Constant Specifies the animation curve type.  Default is linear. Other options include standard curves or an array of coordinates for control points of a cubic bezier curve.
from Number Starting value of number
to Number Ending value of number
duration Number Duration of animation in seconds.
currentValue Number Starting value for number.  Can be used to resume partially complete animations or reverse cancelled animations.
Mojo.Animation.queueForElement(element)

Returns a reference to the appropriate animation queue to use for specified DOM element.

Argument Type Description
element Element  
Mojo.Assert top
Article Title
Mojo.assert(expression, message, messageProperties)

Writes an error to the log if expression doesn't evaluate to true.

Mojo.require and Mojo.assert methods are very similar.  The difference is that Mojo.require methods will throw an exception when their requirements aren't met, and are intended to be used in cases where the application cannot reasonably continue if the requirements aren't met.

Returns String containing the error message written to the log.

Parameter Type Description
expression Expression Expression that must evaluate to true.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Mojo.assertArray(expectedArray, message, messageProperties)

Writes an error to the log if expectedArray fails the Prototype isArray method. Returns String containing the error message written to the log.

Parameter Type Description
expectedArray Object Object to be checked to be an array.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Mojo.assertClass(object, constructorFunction, message, messageProperties)

Writes an error to the log if targetObject wasn't constructed by the passed in constructor function. Returns String containing the error message written to the log.

Parameter Type Description
object Object Object to check for constructing function.
constructorFunction Function Expected constructor function.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.assertDefined(value, message, messageProperties)

Writes an error to the log if value evaluates to undefined.  Returns String containing the error message written to the log.

Parameter Type Description
value Object Value that must not evaluate to undefined.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.Event.listen=function listen(target,type,handlerFunction,useCapture){
  Mojo.assertDefined(target,"Mojo.Event.listen: 'target' parameter must be defined.");
  Mojo.assertString(type,"Mojo.Event.listen: 'type' parameter must be a string.");
  Mojo.assertFunction(handlerFunction,"Mojo.Event.listen: 'handlerFunction' parameter must be a function.");
  target.addEventListener(type,handlerFunction,!!useCapture);
};
Mojo.assertElement(expectedElement, message, messageProperties)

Writes an error to the log if expectedElement fails the Prototype isElement method. Returns String containing the error message written to the log.

Parameter Type Description
expectedElement Object Object to be checked to be a element.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.View.makeFocusable = function(targetElement) {
    Mojo.assertElement(targetElement, "Mojo.View.makeFocusable requires an element.");
    targetElement.setAttribute("tabindex", "0");
};
Mojo.assertEqual(expected, actual, message, messageProperties)

Writes an error to the log if expected != actual. Returns String containing the error message written to the log.

Parameter Type Description
expected Anything The expected value.
actual Anything The actual value.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Mojo.assertFalse(expression, message, messageProperties)

Writes an error to the log if expression evaluates to true. Returns String containing the error message written to the log.

Parameter Type Description
expression Object Expression that must evaluate to false.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

    var details = this.detailsTable.get("5551212");
    Mojo.assertFalse(details, "Details must not be found");
Mojo.assertFunction(expectedFunction, message, messageProperties)

Writes an error to the log if expectedFunction fails the Prototype isFunction method. Returns String containing the error message written to the log.

Parameter Type Description
expectedFunction Object Object to be checked to be a function.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.Event.listen=function listen(target,type,handlerFunction,useCapture){
  Mojo.assertDefined(target,"Mojo.Event.listen: 'target' parameter must be defined.");
  Mojo.assertString(type,"Mojo.Event.listen: 'type' parameter must be a string.");
  Mojo.assertFunction(handlerFunction,
     "Mojo.Event.listen: 'handlerFunction' parameter must be a function.");
  target.addEventListener(type,handlerFunction,!!useCapture);
};
Mojo.assertMatch(regex, testValue, message, messageProperties)

Writes an error to the log if regex doesn't match testValue.

Writes an error to the log if expectedString fails the Prototype isString method. Returns String containing the error message written to the log.

Parameter Type Description
regex Regex Regular expression to match.
textValue String String to match against regex.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.assertNumber(expectedNumber, message, messageProperties)

Writes an error to the log if expectedNumber fails the Prototype isNumber method. Returns String containing the error message written to the log.

Parameter Type Description
expectedNumber Object Object to be checked to be a number.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.assertProperty(properties)

Writes an error to the log if targetObject doesn't have the values for the property name or names passed and throws an exception.

Parameter Type Description
properties String|Array

String: Name of property to check.

Array: Array of strings containing names of properties to check.

 

Mojo.assertString(expectedString, message, messageProperties)

Writes an error to the log if expectedString fails the Prototype isString method. Returns String containing the error message written to the log.

Parameter Type Description
expectedString Object Object to be checked to be a string.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Mojo.Char top
Article Title
Mojo.Char.isDeleteKey(key)

Returns boolean True if key is the delete key and False if not.

Parameter Type Description
key Number Key value to be checked.
Mojo.Char.isEnterKey(key)

Returns boolean True if key is the enter key and False if not.

Parameter Type Description
key Number Key value to be checked.
Mojo.Char.isValidWrittenChar(keyCode)

No info yet.

Mojo.Controller top
Article Title
Mojo.Controller.errorDialog

 

Mojo.Controller.showAlertDialog

 

Mojo.Controller.getAppController

 

Mojo.Controller.showDialog

 

Mojo.Controller.AppController top
Article Title
Mojo.Controller.AppController.closeAllStages()

Closes all stages.

Mojo.Controller.AppController.closeStage(stageName)

Closes the specified stage.

Argument Type Required Default Description
stageName String Required None Name of the stage to close.

 

Mojo.Controller.AppController.createStageWithCallback(stageArguments, onCreate, optionalStageType)

Creates a new stage and calls the specified function when the stage has completed loading.  Data can be bound to the callback function as needed, eliminating the need to pass parameters in the URI. The callback function can use the passed-in stage controller to push the first scene of the new stage.

Argument Type Description
stageArguments String|Object String: the name of the new stage; replaces any existing stage with this name.  Object: Must have a name property containing the name of the new stage. May have an assistantName property to specify the stage assistant and a height property to specify the height of a popup alert.
onCreate Function Function called when the stage is loaded.  The stage controller of the new stage is passed as the first parameter.
optionalStageType String The type of the new stage.  See Mojo.Controller.StageType for allowed values.
Mojo.Controller.AppController.getActiveStageController(stageType)

Returns the stage controller of the currently active (in focus) stage.

Argument Type Description
stageType String Optional; limits focused stage returned to specified type.  See Mojo.Controller.StageType for allowed values.
Mojo.Controller.AppController.getScreenOrientation()

Returns the orientation of the physical screen.

Returns "up", "down", "left", or "right".

 

Mojo.Controller.AppController.getStageController(stageName)

Function to get the stage controller for a specified stage. Returns undefined if the stage does not exist or is not yet initialized.

Argument Type Description
stageName String The name of the stage for which to return the stage controller.
Mojo.Controller.AppController.getStageProxy(stageName)

Returns a controller or proxy object for a stage. Returns the stage controller if available; if not, a proxy object will be returned which implements delegateToSceneAssistant(), and will delegate the calls as expected when the stage is available.

Argument Type Description
stageName String The name of the stage for which to return the stage controller or proxy object.
Mojo.Controller.AppController.launch(appId, params, onSuccess, onFailure)

Launches another application with parameters (optional).

Parameter Type Description
appId String Application ID of the application to launch.
params Object Parameters to send to the launched application.
onSuccess Function Function to be called called if the application is launched successfully. (optional)
onFailure Function Function to be called called if the application launch fails. (optional)
Mojo.Controller.AppController.open(params, onSuccess, onFailure)

Attempts to "open" a file specified in the launch parameters.  If no application can be found, the method fails.  Returns the Mojo.Service.Request object used to make the launch request.

Argument Type Description
params Object Parameters to send to the launched application, including the name of the file to be launched.
onSuccess Function Function called if the file is opened successfully. (optional)
onFailure Function Function called if the file open fails.
Mojo.Controller.AppController.playSoundNotification(soundClass, soundFile)

Plays a sound.

Argument Type Description
soundClass String The class of the sound to be played.
soundFile String Relative or absolute path to the sound file to be played.
Mojo.Controller.AppController.removeAllBanners()

Removes all pending banner messages. Does not affect messages that are already displayed.

Mojo.Controller.AppController.removeBanner(category)

Deletes a pending banner. The category parameter defaults to 'banner'. Will not remove messages that are already displayed.

Argument Type Description
category String The category of the pending banner to be deleted.
Mojo.Controller.AppController.sendToNotificationChain(notificationData)

Propagates notificationData and calls considerforNotification on everyone in the commander stack of the focused window (usually includes the scene assistant, stage assistant and app assistant). As the notificationData propagates through the chain, each assistant (before the app assistant) should remove any properties not needed for building a notification and return the remaining data, which can then be used by the app assistant's considerForNotification function to call showBanner or create or update a dashboard stage.

Mojo.Controller.AppController.showBanner(bannerParamsbannerParams, launchArguments, category)

Shows a banner containing the message text from bannerParams. launchArguments will be used to launch or relaunch the application if the banner is tapped by the user. 

Argument Type Description
bannerParams String|Object

String: Text displayed on banner

Object: Contains the following properties:

messageText: Text displayed on banner

soundClass: string containing name of sound class to use.

soundFile: relative or full path to sound file to play

icon: relative or full path to icon to be displayed with banner

launchArguments

String

Arguments sent to the application when it is launched or re-launched after the banner is tapped.
category String Banners of the same category replace other banners of the same cateogry in the banner queue.  A banner that is in the process of being displayed to the user cannot be replaced whether or not it is of the same category.  Defaults to 'banner'.
Mojo.Controller.SceneController top
Article Title
Mojo.Controller.SceneController.listen(element, eventType, callback, onCapture)

Wrapper around Mojo.Event.listen that also calls get() on the element parameter if it is a string, converting it to a DOM node.

Argument Type Description
element String|Element

String: DOM ID identifying the target element

Element: Element reference to the target element.

eventType String String identifier for the event type
callback Function Function called when the event occurs
onCapture Boolean

True to listen during the capture phase; False to listen during bubbling (optional)

Mojo.Controller.SceneController.pushContainer(container, layer, options)

Pushes a new container on the container stack of the calling scene. Mojo.Event.key* events are sent to the top container. All containers with a lower or same layer will be cancelled if they specified a cancelFunc in their options. 

Argument Type Description
container Element The container to be pushed.
layer String Constant indicating the layer of the container being pushed.  Usually dialogContainerLayer or submenuContainerLayer.
options Object Specifies optional arguments.  May contain a cancelFunc property that is called when the container is cancelled.
Mojo.Controller.SceneController.removeCommander(cmdr)

Removes a commander from the commander stack.

Argument Type Description
cmdr Object Commander to remove from the stack.
Mojo.Controller.SceneController.removeContainer(container)

Removes the specified container element from the stack. Returns True if successful.

Argument Type Description
container Element Container to be removed
Mojo.Controller.SceneController.removeRequest(request)

Remove a request from the scene's list of requests.

Argument Type Description
request Object Request to be removed
Mojo.Controller.SceneController.removeWatcher(watcher, model)

Removes a specified model watcher. If model is undefined, then the specified watcher is removed from all models.

Called by the framework when re-rendering HTML that includes widgets so that the old/removed widgets are not notified of changes to models.

Argument Type Description
watcher Object The object owning changeFunc specified when watchModel was called.
model Object Model name.  If undefined, all registered model watchers for the given watcher are removed.
Mojo.Controller.SceneController.sceneContainerLayer

Constant

For standard pushContainer layers.

Mojo.Controller.SceneController.setInitialFocusedElement(focusedElement)

Called by the scene assistant during setup to specify the element that will receive focus.

Argument Type Description
focusedElement String|Element|null

String: elementID to focus

Element: Element to focus

Null: Prevents automatic focus on any element

Mojo.Controller.SceneController.setupWidget(name, attributes, model)

Register the given attributes and model to be used with the widget of the given name.  For details on specific widgets with examples, refer to the UI Widget list.

Called by scene assistants in the setupViews() method.  If a model is specified for a widget rendered in a list item, the model will be overridden by the one defined for the list item.

Argument Type Description
name Object  
attributes Object  
model Object  
Mojo.Controller.SceneController.setWidgetModel(widget, model)

Sets the data model for a widget and notifies the widget of the new model.

Widget can be specified by either DOM element or ID but not widget name, as it is intended to operate on single widget only. The setup associated with the widget is not modified.

Argument Type Description
widget Object The widget whose model is to be changed
model Object The new model to be applied to the widget
Mojo.Controller.SceneController.showWidgetContainer(elementOrId)

Used to notify widgets that a div containing widgets has become visible. This is important for getting correct measurements where widgets are dependent upon them for drawing.

Argument Type Description
elementOrId    

 

Mojo.Controller.SceneController.stopListening(element, eventType, callback, onCapture)

Wrapper around Mojo.Event.stopListening that also calls get() on element if it is a string, converting it to a DOM node.

Argument Type Description
element String|Element

String: DOM ID

Element: DOM element reference

eventType String Identifier for the event type.
callback Function Function object registered to be called when the event occured.
onCapture Boolean True to listen during capture phase, False to listen during bubbling.
Mojo.Controller.SceneController.topContainer()

Returns the top container in the calling scene.

Mojo.Controller.SceneController.useLandscapePageUpDown(yesNo)

Enables and disables receiving page up and page down key events in response to the "swipe" gesture when the scene is in landscape mode. This property is persistent for each scene.

Argument Type Description
yesNo Boolean True enables page up/down key events for the calling scene; False disables.

Mojo.Controller.SceneController.watchModel(model, who, changeFunc)

Sign up for notifications when changes are made to the specified model.

When someone calls modelChanged on the specified model, the changeFunc will be called. Usually used by the framework to automatically notify widgets when their models change.

Argument Type Description
model Object The model to watch for changes.
who Object The object that owns the changeFunc. Used to ensure that objects are not notified of their own changes to the model and that changeFunc is called in the context of who.
changeFunc Object Function called when modelChanged is called on model.
Mojo.Controller.SceneController.commitChanges()

 

Mojo.Controller.SceneController.enableFullScreenMode(yesNo)

Enables and disables full screen mode for the scene. This property is persistent for each scene, so it is not necessary for client code to manage it.

Argument Type Description
yesNo Boolean True to enable fullscreen mode.  False to disable fullscreen mode.  Applies to calling scene only.
Mojo.Controller.SceneController.get(elementId)

 

Mojo.Controller.SceneController.getSceneScroller()

Returns the scene scroller created automatically with every scene.

Mojo.Controller.SceneController.hideWidgetContainer(elementOrId)

Notifies widgets that a div containing widgets has changed its CSS visibility property to display:none. This is important for getting correct measurements where widgets are dependent upon them for drawing.

Argument Type Description
elementOrId String|Element  
Mojo.Controller.SceneController.modelChanged(model, who)

Can be called when a data model changes and a widget displaying that data needs to be updated.

Argument Type Description
model Object Model object that changed
who Object Object that changed the model.  Usually the widget object or scene assistant. Used to avoid notifying objects of their own changes to a model in the case where both the scene assistant and widget change & watch the same model.

Note: Palm states this API is still changing. Eventually, they want to provide a more structure on the datamodel side and an API that allows the app to express what about the model changed.

For example, added or removed an element, modified one or more properties of an element, etc.

Mojo.Controller.SceneController.popupSubmenu()

Popup submenus can be used to provide a text list of choices to the user. It accepts standard menu models with a few additional optional properties.

Example usage:

    sceneController.popupSubmenu(this.controller, {
onChoose:this.popupChoose,
placeNear:clickEvent.target,
items: [{label: $L('Apply'), command: 'apply-cmd'},
{label: $L('Applique'), command: 'applique-cmd'},
{label: $L('Applaud'), command: 'applaud-cmd'},
{label: $L('Approximate'), command: 'approx-cmd'}]
});

The above code will cause a modal list to appear with the label choices presented. When the user taps one, the onChoose function will be called in the scope of the scene assistant with the command property of the chosen item. If the user taps outside the popup menu, the menu is dismissed and the onChoose function is called with undefined.

Beyond the standard menu model properties, the submenu supports some additional model properties:

Property Type Description
onChoose Function Called when the user makes a choice from the menu
placeNear Element Used to position the submenu near a specified element (optional)
toggleCmd   Causes appropriate item to appear with a checkmark.  Supported in top-level popup model. (optional)
popupClass String CSS class for popup menu (optional)
scrimClass String CSS class for popup scrim.  Defaults to submenu-popup. (optional)
manualPlacement Boolean True to prevent popup from being placed automatically (centered or near specified placeNear element)

Beyond the standard menu item properties, the submenu supports some additional menu item properties:

Argument Type Description
secondaryIcon String CSS class for a secondary icon to be displayed.  Usually used for displaying status.  Appears to the left of the menu item. (optional)
secondaryIconPath String Like iconPath, but for secondaryIcon (optional)
chosen Boolean Causes item to be styled as selected item in a toggle group (optional)

Keyboard shortcuts can be displayed in the submenu, but are implemented by the main menu system.

 

Mojo.Controller.SceneController.prepareTransition(transitionType, isPop, transitionType, isPop)

Creates a Transition object that can be used to run a transition within the scene. On creation, events to the scene are frozen and a snapshot of the scene's window is taken. Any processing to change the scene's state should be done prior to calling run() on the Mojo.Transition object. After run() is called, events will once again behave as normal.

Argument Type Description
transitionType String The type of transition to run.  Optional.  Transition types include: Mojo.Transition.none, Mojo.Transition.zoomface, Mojo.Transition.crossFade, Mojo.Transition.defaultTransition
isPop Boolean True if the current scene is being popped.

Example usage:

    var transition = this.controller.prepareTransition(Mojo.Transition.crossFade, false);
// Code setting up the scene's new state goes here
transition.run();

 

Mojo.Controller.SceneController.pushCommander(cmdr)

Adds the given commander to the top of the calling scene's SceneController stack. The commanders in this stack are only used when this scene is the current scene.

Argument Type Description
cmdr Object Commander to add to the stack.

 

Mojo.Controller.SceneController.serviceRequest(url, options, resubscribe)

Creates a Palm service request.  See the Service API section for details and examples of specific service calls.  The request is automatically cancelled when the scene is popped. The parameters are passed directly to new Mojo.Service.Request().

Argument Type Description
url String URL of the service request
options Object Object containing options for the request
resubscribe Boolean True automatically resubscribes when an error is received from the service
Mojo.Controller.SceneController.setDefaultTransition(transitionType)

Sets default transition to be used for pushing or popping the calling scene. This transition can be overridden by an option specified when pushing or popping the scene.

Argument Type Description
transitionType String Transition name from Mojo.Transition.
Mojo.Controller.SceneController.setUserIdleTimeout(element, func, delay, watchMouse, watchKeys)

Function to call a function after the user has been idle for a specified amount of time. Once set, the timeout will remain dormant until the user has been continuously idle for the delay specified. Returns Function.  Calling Function cancels idle timeout.

Argument Type Description
element String|Element Element to watch for user events.  Can be SceneController.sceneElement or a specific element.  ID or Element itself is accepted.
func Function The function called after the delay has been reached.
delay int Delay in milliseconds after the last user event is detected on element before calling func.
watchMouse Boolean True to watch for screen touches and taps.  Default is True.
watchKeys Boolean True to monitor keyboard input. Default is True.
Mojo.Controller.StageController top
Article Title
Mojo.Controller.StageController.unloadStylesheet(path)

Unloads a stylesheet and any versions of it for the current locale from the stage's document.

Argument Type Description
path String Relative path (from the application's root) to the stylesheet to be unloaded.
Mojo.Controller.StageController.activate()

Programatically activates the calling stage and causes card window to be maximized.

Mojo.Controller.StageController.activeScene()

Returns the currently active scene from this stage, if any. If no scenes are active, returns undefined.

Mojo.Controller.StageController.deactivate()

Programatically deactivates this stage and causes card windows to be minimized.

Mojo.Controller.StageController.delegateToSceneAssistant(functionName)

Function to call a method on the assistant of the active scene (of the current stage).

Argument Type Description
functionName Object Name of the property that contains the function to call. Any additional parameters are passed to that function. this is bound to the scene assistant for this call.
Mojo.Controller.StageController.getAppController()

Return the current application controller.

Mojo.Controller.StageController.getScenes()

Returns an array containing the scene controllers currently on the stack. result[0] is the first (bottom) scene.

Mojo.Controller.StageController.getWindowOrientation()

Gets the orientation of the stage's window. Returns 'up', 'down', 'left', or 'right'.

Mojo.Controller.StageController.hasNewContent()

Function to find out if the current stage has new content.  Returns Boolean.

Mojo.Controller.StageController.indicateNewContent(hasNew)

Makes the device's center navi button pulsate if hasNew is true. Can be used for anything but mainly intended to alert the user to dashboard events.

Argument Type Description
hasNew Boolean

Set to True to pulsate.


Mojo.Controller.StageController.isActiveAndHasScenes()

Function to find out if the calling stage is active and has pushed scenes.  Returns Boolean.

Mojo.Controller.StageController.isChildWindow()

Function to find out if the current window is a child window.  Returns Boolean.

Mojo.Controller.StageController.loadStylesheet(path)

Loads a stylesheet and any versions of it for the current locale into the stage's document.

Argument Type Description
path String Relative path (from the application root) to the stylesheet to be loaded.

 

Mojo.Controller.StageController.parentSceneAssistant(targetSceneAssistant)

Returns the assistant of the scene below this scene in the scene stack, or undefined if this is the root scene.

Argument Type Description
targetSceneAssistant    

Mojo.Controller.StageController.popScene(returnValue, options)

Removes a scene from the scene stack, passing returnValue to the newly revealed scene's activate method. This is an asynchronous operation.

Argument Type Description
returnValue Object Object passed to the activate method of the scene below the scene being popped.
options    
Mojo.Controller.StageController.popScenesTo(targetScene, returnValue, options)

Removes scenes from the scene stack until the specified scene is reached or all scenes have been removed from the stack, whichever comes first. The targetScene object may be either the SceneController for the target scene, the scene's DOM ID, or the scene's name. If targetScene is undefined, all scenes are popped. Popped scenes are not reactivated and there is no visual transition to signify they are being removed from the stack. This is an asynchronous operation.

Argument Type Description
targetScene String|Object

String: Name of target scene or DOM ID

Object: SceneController for target scene

returnValue    
options Object  
Mojo.Controller.StageController.pushCommander(cmdr)

Adds the provided commander to the top of the calling stage's StageController stack. The stack contains commanders that are used only with the current scene.

Argument Type Description
cmdr Object Commander object to push onto the stack.
Mojo.Controller.StageController.pushScene(sceneArguments)

Pushes a new scene. After this call, the new scene is placed on the stage's scene stack, the scene assistant's setup method is called and UI widgets are instantiated. The scene is then displayed and the scene assistant's activate method is called.

Argument Type Description
sceneArguments String|Object

String: Name of the scene to push

Object: Properties include:

Name of the scene

ID to use as DOM ID

Additional arguments that arepassed to the constructor of the scene assistant.


Mojo.Controller.StageController.removeCommander(cmdr)

Removes a commander from the commander stack.

Argument Type Description
cmdr Object Commander to be removed
Mojo.Controller.StageController.sendEventToCommanders(event)

Sends the given event through the entire command chain, starting with the CommanderStack in the current scene and progressing to the StageController's stack.  Is stopped if a scene in the command chain calls event.stopPropagation().

Argument Type Description
event Object  

Mojo.Controller.StageController.setClipboard(escapeHTML:, escapeHTML)

Enables the client application to send text to the clipboard.  Currently selected text automatically passed as first argument.

Argument Type Description
escapeHTML Boolean True removes rich text formatting in copied text.  False preserves rich text formatting.  Currently not implemented in webOS 1.1.
Mojo.Controller.StageController.setWindowOrientation(orientation)

Sets the orientation of the stage's window.

Argument Type Description
orientation String Available values: up, down, left, right and free
Mojo.Controller.StageController.swapScene(sceneArguments)

Pops the current scene and simultaneously pushes a new scene without activating & deactivating any underlying scenes. This is an asynchronous operation.

Argument Type Description
sceneArguments String|Object

String: Name of scene to push

Object: Containing properties:

Name of scene to push

ID to use as a DOM ID.


Mojo.Controller.StageController.topScene()

Returns the topmost scene from the calling stage.

Mojo.Depot top
Article Title
Mojo.Depot.add(key, value, onSuccess, onFailure)

Function to add an object identified by a key to the depot. The default bucket is used.

Parameters Type Description
key String Key to identify the object being stored in the depot.  If an object already exists with the same key, it is replaced
value Object Object to store in the depot
onSuccess Function Function called when the object is successfully stored in the depot
onFailure Function Function called if the add fails.  Passed an error string.

Example usage:

db = new Mojo.Depot({name:"feedDB", version:1, estimatedSize:25000, replace: false}, 
     this.dbOpenOK.bind(this), this.dbOpenFail.bind(this)); 

db.add("feedList", feedList, 
        function() {Mojo.Log.info("........","feedList saved OK");}, 
        function(transaction,result) { 
          Mojo.Log.warn("Database save error (#", result.message, ") - can't save feed list. Will need to reload on next use."); 
          Mojo.Controller.errorDialog("Database save error (#" + result.message + ") - can't save feed list. Will need to reload on next use."); 
        });
Mojo.Depot.discard(key, onSuccess, onFailure)

Function to remove an object identified by key from the depot. The default bucket is used.

Parameters Type Description
key String Key to identify object to be removed from the depot.
onSuccess Function Function called if the object is successfully removed
onFailure Function Function called if an error occurs and the object is not removed from the depot.  Passed an error string.
Mojo.Depot.get(key, onSuccess, onFailure)

Function to retrieve an object identified by key from a depot. The default bucket specified by _defaultBucketName is used.

Parameters Type Description
key String Key to identify the object to be retrieved from the depot.
onSuccess Function Function called if the object is successfully retrieved.  Function is passed the retrieved object as its first parameter.  If no object found for specified key, null is passed to function.
onFailure Function Function called if retrieval fails.  Function is passed an error string as its only argument.

Example usage:

db = new Mojo.Depot({name:"feedDB", version:1, estimatedSize:25000, replace: false}, 
     this.dbOpenOK.bind(this), this.dbOpenFail.bind(this)); 
FeedListAssistant.prototype.dbOpenOK = function() { 
    Mojo.Log.info("........","Database opened OK"); 
    db.get("feedList", this.updateList.bind(this), 
      this.useDefaultList.bind(this)); 
}; 
Mojo.Depot.remove(bucket, key, onSuccess, onFailure)

Function to remove an object identified by bucket and key from the depot.

Parameters Type Description
bucket String Bucket identifying the namespace of key; if null or not specified, _defaultBucketName is used.
key String Key identifying object to be removed from depot
onSuccess Function Function called if object successfully removed
onFailure Object Function called if object failed to be removed.  Passed error string.
Mojo.Depot.removeAll(onSuccess, onFailure)

Function to delete the data from the current depot database.

Argument Type Description
onSuccess Function Function called when the data is successfully deleted
onFailure Function Function called if the data could not be deleted

Example usage:

db = new Mojo.Depot({name:"feedDB", version:1, estimatedSize:25000, replace: false}, 
     this.dbOpenOK.bind(this), this.dbOpenFail.bind(this))
db.removeAll(); 
Mojo.Depot(options, onSuccess, onFailure)

Depot allows you to store JavaScript objects in a database. Currently implemented as a framework wrapper around HTML5 active record access.

Parameters Type Description
options Object Options for creating/opening a depot
onSuccess Function Function called if depot is created or opened successfully
onFailure Function Function called if depot fails to be created or opened.  Passed error string.

options object properties:

Property Type Description
name String Name of the depot.  Currently mapped to an HTML5 database name.
version Number Version for the depot. (optional)
displayName String Name displayed in the UI for the database.  Not currently used. (optional)
estimatedSize Number Estimated size of the database. (optional)
replace Boolean True to cause any existing data for the depot being opened to be deleted and a new, empty depot to be created.  Defaults to False.
filters Array Array of strings that objects in the depot can use as filters (optional)
identifiers {String:(Function|Object), ...} Hash containing key-value pairs of identifiers with either constructor functions or objects whose constructor functions will be used (optional)

Example usage:

var db= new Mojo.Depot ({name:”myDB”,version:1,replace:false}, this.openOK, this.openFail);
FeedListAssistant.prototype.dbOpenOK = function() { 
    Mojo.Log.info("........","Database opened OK"); 
    db.get("feedList", this.updateList.bind(this), 
      this.useDefaultList.bind(this)); 
}; 
FeedListAssistant.prototype.dbOpenFail = function(transaction, result) { 
    Mojo.Log.warn("Can't open feed database (#", result.message, "). All feeds will be reloaded."); 
    Mojo.Controller.errorDialog("Can't open feed database (#" + result.message + "). All feeds will be reloaded."); 
 }; 
Mojo.Drag top
Article Title
Mojo.Drag.setupDropContainer(element, dropClient)

Configures the specified element as a valid drop container for dragged items.

Parameter Type Description
element String DOM element to be made a drop container for dragged items
dropClient Object An object with additional drop container properties

dropClient object properties:

Property Type Description
dragEnter Function Function called the moment an item enters the space occupied by this container. Passed the DOM element being dragged.
dragHover Function Function called when an item moves over this container.  Passed the DOM element being dragged.
dragLeave Function Function called the moment an item leaves the space occupied by this container.  Passed the DOM element being dragged.
dragDrop Function Function called when an item is dropped on this container.  Passed the DOM element being dragged and the Boolean value newItem indicating whether the item came from a different container.
dragRemove Function Function called when an item in this container is dropped on a different container.
dragDatatype String Only draggers with a matching datatype can be enter or be dropped on this container.  Optional
Mojo.Drag.startDragging(sceneController, element, startEvent, options)

Function used to start dragging an element. Called when a hold event occurs (for elements dragged on push-and-hold) or on mousedown or dragStart.  Returns an active "dragger" object when the user's finger is down and before the dragStart event actually occurs.

The dragger sets the scene up for dragging, preventing the drag from causing the scene to be scrolled. Both dragEnd and tap events cause the drag operation to end, since dragStart and dragEnd events cannot occur if there are no mousemove events. This sort of "aborted" drag operations are treated like any other, and will still cause the appropriate enter & drop methods to be called on the container.

Parameters Type Description
sceneController String Controller for the scene containing the element to be dragged
element String DOM element ID to begin dragging
startEvent Event User event that began the drag.
options Object Additional drag options.  See below.

options object properties:

Property Type Description
draggingClass String CSS class to apply to the dragged element during dragging.  Removed when dragging ends.
preventVertical Boolean True prevents dragging in the vertical direction.  Default is False.
preventHorizontal Boolean True prevents dragging in the horizontal direction.  Default is False.
allowExit Boolean True allows the element to be dragged into containers other than its own. Default is False.
preventDropReset Boolean True prevents the object from returning to its original position when dropped.  To return the object to its original position with this option enabled, call resetElement() on  dragger.
datatype String The dragged element can only be dropped on containers specifying the same datatype.
autoscroll Boolean True to automatically scroll the scene when the dragged element(s) reach the edge of the visible area.
maxHorizontalPixel Integer Maximum horizontal position the object can be dragged to (in pixels)
minHorizontalPixel Integer Minimum horizontal position in pixels the object can be dragged to (in pixels)
maxVerticalPixel Integer Maximum vertical position the object can be dragged to (in pixels)
minVerticalPixel Integer Minimum vertical position the object can be dragged to (in pixels)
Mojo.Event top
Article Title
Mojo.Event.aboutToActivate

Generated before a scene is displayed. Allows widgets or scenes to delay the scene transition if needed.

Supported Widgets

  • None.
Mojo.Event.activate

An activate event is generated when a scene is loaded.

Supported Widgets

  • None
Mojo.Event.back

This event is sent through the active commander chain when a back gesture is recognized (or the back key is pressed on the desktop).

It's currently generated by the stage assistant, which also responds to it in handleCommand(). If no other clients handle the event, then the stage assistant will do so by closing the current dialog or popping the current scene.

Custom Event Fields

  • originalEvent: The original click Event object which caused this event to be dispatched. Useful for disambiguating changes if the list items contain multiple input fields.

Supported Widgets

  • None.
Mojo.Event.command

A command event is generated when a menu item is selected.

Supported Widgets

  • None.

 

Mojo.Event.commandEnable

Menuitems that specify checkEnabled:true in the menu model cause the menu system to check their enable state before displaying them. This is useful for items in submenus and the appmenu, because they are not constantly displayed (like items in the command & view menus), meaning their enable state always appears correct when the menu is popped up.

The command-enabled event is generated as part of menu updating.
To check the enable state of a menuitem, a command-enable event is sent through the commander chain. This event does not go through the DOM.
If nothing in the commander chain calls preventDefault() on the event, the menuitem will be enabled.

Supported Widgets

  • None.
Mojo.Event.dragEnd

An up action following a Mojo.Event.dragStart event generates a dragEnd event.

Supported Widgets

  • None.
Mojo.Event.dragging

Movement following the Mojo.Event.dragStart event generates dragging events.

Supported Widgets

  • None.

 

Mojo.Event.dragStart

A down action followed by movement outsided of a system-defined radius generates a Mojo.Event.dragStart event. Usually, the Mojo.Event.dragStart event is handled by the scroller. However, any element that chooses to handle this event gets all subsequent drag events.

Supported Widgets

  • None.
Mojo.Event.filter

Entering data in the filterbox generates a filter event after a client of default specified delay.

Supported Widgets

  • Mojo.Widget.FilterField
Mojo.Event.filterImmediate

Entering data in the filterbox generates a filter event as soon as a key is typed.

Supported Widgets

  • Mojo.Widget.FilterField
Mojo.Event.flick

Movement greater than a system-defined rate, between down and up events, generates a flick event.

Supported Widgets

  • None.
Mojo.Event.forward

This event is sent through the active commander chain when a forward gesture is recognized

Supported Widgets

  • None.
Mojo.Event.hold

A down movement lasting greater than a system-defined time interval and with movement within a limited radius generates a hold event. The hold event is associated with the Mojo.Event.hold event.

Supported Widgets

  • None.
Mojo.Event.holdEnd

An up movement following a hold event generates a Mojo.Event.holdEnd event.

Supported Widgets

  • None.
Mojo.Event.imageViewChanged

imageViewChanged sent from an ImageView widget when the current center image has been changed via a gesture.

Supported Widgets

  • Mojo.Widget.ImageView
Mojo.Event.keydown

Forwarded keydown event. Only supported on the currently active sceneElement or container.

Custom Event Fields

  • originalEvent: keyboard event that triggered this event.

Supported Widgets

  • None.
Mojo.Event.keypress

Forwarded keydown event. Only supported on the currently active sceneElement or container.

Custom Event Fields

  • originalEvent: keyboard event that triggered this event.

Supported Widgets

  • None.
Mojo.Event.keyup

Forwarded keyup event. Only supported on the currently active sceneElement or container.

Custom Event Fields

  • originalEvent: keyboard event that triggered this event.

Supported Widgets

  • None.
Mojo.Event.listAdd

This event is dispatched to the widget element when there the special "Add" item at the end of the list is clicked. This item appears when the addItemLabel property is defined in the widget's attributes or model, and a custom event name is used to give applications an easy way to identify the expected behavior.

Custom Event Fields

  • model: The model object used to render the SmallList to which an item should be added.
  • originalEvent: The original click Event object which caused this event to be dispatched. Useful for disambiguating changes if the list items contain multiple input fields.
  • item: The item model to be added. Only defined for listAdd events resulting from a drag/drop from a different list.
  • index: The index at which to add the new item. Only defined for listAdd events resulting from a drag/drop from a different list.

Supported Widgets

  • Mojo.Widget.List
Mojo.Event.listChange

This event is dispatched to the widget element when a list item is clicked. As with Mojo.Event.listTap, the app handler is responsible for sorting out which part of the list item changed if there are multiple options, and event.originalEvent.target should be the input element which changed.

Custom Event Fields

  • object: The object from the listItems array in the model associated with the changed list item.
  • model: The model object used to render the SmallList.
  • originalEvent: The original change Event object which caused this event to be dispatched. Useful for disambiguating changes if the list items contain multiple input fields.

Supported Widgets

  • Mojo.Widget.List
Mojo.Event.listDelete

This event is dispatched to the widget element when an item is deleted from the list. SceneAssistants will often listen for this event on List widgets, and should respond by deleting the given item from the model (and database, if any). If preventDefault() is called on the listDelete event, then the default deletion behavior in the list widget will not occur.

Custom Event Fields

  • model: The widget's model object.
  • item: The model object for the list item being deleted.
  • index: The index of the list item being deleted.

Supported Widgets

  • Mojo.Widget.List
Mojo.Event.listen(target, type{string}, handlerFunction, useCapture)

A wrapper around addEventListener that adds some parameter checking.

Parameter Type Description
target Element Target to observe
type String Type of event to observe
handlerFunction Function Function that is called when the event occurs
useCapture Boolean True causes event to be observed during the capture phase.  Optional.

Example usage:

        // Setup the TruncTextField widget
        var scratchEventDiv = this.controller.get('scratch_event');
        this.controller.setupWidget('scratch_event_field', tfAttrs, this.scratchEvent);
        this.controller.instantiateChildWidgets(scratchEventDiv);
        this.scratchEventField = this.controller.get('scratch_event_field');
        this.scratchEventCommitHandler = this.handleEditScratchEventCommit.bind(this);
        this.scratchEventKeyEventHandler = this.handleScratchEventKey.bind(this);
        this.scratchEventTapHandler = this.handleScratchEventTap.bind(this)
        this.scratchEventHoldHandler = this.handleScratchEventHold.bind(this);
        
        // Listen for the key and tap events on the whole scene when a 
        // scratch event is present
        Mojo.Event.listen(scratchEventDiv, "keyup", this.scratchEventKeyEventHandler);
        Mojo.Event.listen(this.controller.sceneElement, 
             Mojo.Event.tap, this.scratchEventTapHandler);
        Mojo.Event.listen(this.controller.sceneElement, 
             Mojo.Event.hold, this.scratchEventHoldHandler);
Mojo.Event.listenForFocusChanges(node, handler)

This function can be used to listen for changes in which element has focus inside the specified node.

A listener object is returned which implements a stopListening() method. This can be called tp permanently cancel the listener, removing its event listeners.

Parameter Type Description
node   Node on which to listen for events
handler Function Function called when focus changes.  Passes the newly focused element or null.

 Example usage:

        this.controller.setupWidget('emailAddress', this.emailAttributes, this.emailModel);
                
        $('emailAddress').observe(Mojo.Event.propertyChange, this.emailChanged.bind(this));
        this.emailFocusHandler = this.emailHandler.bind(this);
        Mojo.Event.listenForFocusChanges($('emailAddress'), this.emailFocusHandler);
Mojo.Event.listenForHoldEvent(node, downEvent, upEvent, handler, timeout)

This function can be used to listen for a 'hold' event on a given node. Initiates a hold timer when the appropriate down event is received and cancels the time if the up event occurs before the timer has expired. If the timer expires, the given handler function is called with the initial down event as the first argument.

Returns a listener object which implements a stopListening() method. Calling stopListening() permanently cancels the listener, removing its event listeners. Alternatively, if the handler function returns true, the listener will be automatically stopped.

The implementation is ideal for key events because successive down events do not reset the hold timer. After calling the handler once, it will not be called again until after an up event is received.

Parameter Type Description
node   Node on which to listen for events
downEvent String Type of event that will initiate the hold timer
upEvent String Type of event that will cancel the hold timer
handler Function Function called when the hold timer expires
timeout Integer Length of hold timer in seconds.  Defaults to 1.  Optional.
Mojo.Event.listReorder

This event is dispatched to the widget element when an item is reordered. SceneAssistants will often listen for this event on List widgets, and should respond by reordering the given item model as indicated (and persist the changes to disk if appropriate).

Custom Event Fields

  • model: The widget's model object.
  • item: The model object for the list item being moved.
  • fromIndex: The current index of the list item, which it should be moved from.
  • toIndex: The new index of the list item, which it should be moved to.

Supported Widgets

  • Mojo.Widget.List
Mojo.Event.listTap

This event is dispatched to the widget element when there is a mojo-tap event on a list item. The app handler is responsible for sorting out which part of the list item was clicked if necessary, since that depends entirely on the template provided. It's useful to look at event.originalEvent.target. This is the target of the original click or change event that caused the higher level mojo event to be dispatched. It will be an input element containing the new value for a change event, or the item's sub-element that was actually clicked for a click event. For example:

    listClickHandler: function(event) {
// Only respond to clicks on the label element, not the editable text field.
if(event.originalEvent.target.tagName == "LABEL")
Mojo.Log.info(event.object.data +": "+event.object.definition);
}

Custom Event Fields

  • item: The object from the listItems array in the model associated with the clicked list item.
  • model: The model object used to render the SmallList.
  • originalEvent: The original click Event object which caused this event to be dispatched. Useful for disambiguating clicks if the list items contain multiple clickable elements.

Supported Widgets

  • Mojo.Widget.List
Mojo.Event.orientationChange

Sent by the scene controller on the scene element when the screen orientation changes. Contains an orientation property describing the orientation.

Mojo.Event.progressComplete

Sent when progress reaches 100%.

Supported Widgets

  • Mojo.Widget.ProgressPill
  • Mojo.Widget.ProgressBar
Mojo.Event.progressIconTap

Sent when the icon on the ProgressPill is tapped by the user.

Custom Event Fields - model: model associated with this progress pill.

Supported Widgets

  • Mojo.Widget.ProgressPill
  • Mojo.Widget.ProgressBar
Mojo.Event.propertyChange

This event is dispatched to the widget element when property-editing widgets change values.

Custom Event Fields

  • property: Name of the property that changed.
  • value: New value of the property.
  • model: The model object to which the property change applies. Sometimes available:
  • oldValue: value of the widget before this change.
  • originalEvent: event that triggered the propertyChange event to be sent.

Supported Widgets

  • Mojo.Widget.ListSelector
  • Mojo.Widget.PasswordField
  • Mojo.Widget.RadioButton
  • Mojo.Widget.Scroller
  • Mojo.Widget.Slider
  • Mojo.Widget.TextField
  • Mojo.Widget.ToggleButton
Mojo.Event.scrollStarting

When contained in a scroller, down action followed by movement generates a scroll-starting event.

Supported Widgets

  • Mojo.Widget.Scroller
Mojo.Event.send(element, name{string}, mojoDetails, optionalBubbles, optionalCancel)

Similar to the element.fire() method of the Prototype JavaScript framework, except that the event type can be specified (instead of always dataavailable), and details are placed in the event object directly (instead of a memo subobject). If element is undefined, the new event will just be returned and not actually dispatched.

Parameter Type Description
element Element DOM element to dispatch the event on.
name String Name of the event, visible in event.type.
mojoDetails String Hash of custom event properties to be copied to the event object.
optionalBubbles Boolean True to set the event propagation behavior to bubble.  Defaults to True.
optionalCancel Boolean True to allow the event's default action to be prevented via preventDefault().  Defaults to True.
Mojo.Event.sendKeyDownAndUpEvents(keyDescription, optionalDocument)

Similar to prototype's element.fire(), method, except that the event type can be specified (instead of always dataavailable) and the specified details are placed in the event object directly (instead of a memo subobject). If element is undefined, the new event will just be returned and not actually dispatched.

Parameter Type Description
element Element HTML element to dispatch the event on
name String Name of the event, visible in event.type
mojoDetails String A hash of custom event properties to be copied to the event object
optionalBubbles Boolean True to set the event propagation to bubble.
optionalCancel Boolean True to allow the event's default action to be prevented via the preventDefault() method.

Example usage:

    if (event.keyCode === Mojo.Char.enter) {
        var selection = document.querySelector(':focus');
        if (!Mojo.Gesture.handlesReturnKey(selection)) {
            Event.stop(event);
            Mojo.Event.sendKeyDownAndUpEvents("U+0009");            
        }
    }

 

Mojo.Event.sendKeyEvent(keyDescription, optionalEventType, optionalDocument)

Function to create and send a key event.

Parameter Type Description
keyDescription String Key description for key.  Example: "U+000A" for Enter.  Full list of codes can be found here.
optionalEventType String Event type. Default is keydown.
optionalDocument Element Element to target the event on.  Default is current active document.
Mojo.Event.singleTap

A native down-and-up movement within a limited time interval and within a limited radius generates a single tap event.

It's sent when Mojo.handleSingleTap is called and has the following properties: x, y, shiftKey, ctrlKey, altKey, metaKey, timestamp.

Supported Widgets

  • None.

Mojo.Event.sliderDragEnd

Sent when the draggable element on the Slider is dropped.

Supported Widgets

  • Mojo.Widget.Slider
  • Mojo.Widget.ProgressSlider

 

Mojo.Event.sliderDragStart

Sent when the draggable element on the Slider is picked up to be dragged.

Supported Widgets

  • Mojo.Widget.Slider
  • Mojo.Widget.ProgressSlider

 

Mojo.Event.stageActivate

A stageActivate event is generated when a stage becomes active and is potentially receiving the user's attention. For card stages, this is when the stage is maximized and fills the screen. The event is sent to the top scene, and bubbles up to the stage's document.

Supported Widgets

  • None.
Mojo.Event.stageDeactivate

A stageDeactivate event is generated when a stage is no longer active and potentially receiving the user's attention. For card stages, this is when the stage is minimized.
The event is sent to the top scene, and bubbles up to the stage's document.

Supported Widgets

  • None.
Mojo.Event.tap

A down-and-up movement within a limited time interval and within a limited radius generates a tap event.

Supported Widgets

  • None.
Mojo.Event.make(name{string}, details, optionalDocument, optionalBubbles, optionalCancel)

Function used to create custom mojo events.

In addition to creating an event with the specified name, the event is also extended such that a isDefaultPrevented() method is available.

Parameter Type Description
name String Name of the event, visible in event.type
details String Hash of custom event properties to be copied to the event object.
optionalDocument Element DOM element to target the event on.  Default is current active document.
optionalBubbles Boolean True to set the event propagation behavior to bubble.  Defaults to True.
optionalCancel Boolean True to allow the event's default action to be prevented via preventDefault().  Defaults to True.

Example usage:

      var newEv = Mojo.Event.make(Mojo.Event.back, {originalEvent: event});
      this.sendEventToCommanders(newEv);
      if(newEv.defaultPrevented)
           {Event.stop(event);}
Mojo.Event.stopListening(target, type{string}, handlerFunction, useCapture)

A wrapper around removeEventListener that adds some parameter checking.

Parameter Type Description
target String Target to observe
type String Type of event being observed
handlerFunction Function Function previously passed to listen
useCapture Boolean True causes a capture phase listener to be removed.  Optional.

Example usage:

StartpageAssistant.prototype.deactivate = function() {

    // Stop listening for taps on the start page icons
    Mojo.Event.stopListening(this.controller.get('bookmarks'), 
  Mojo.Event.tap, this._onStartPageTapHandler, true);

    // Cleanup focus handlers.
    this.controller.document.removeEventListener(Mojo.Event.activate, 
  this._onCardActivateHandler, false);
    this.controller.document.removeEventListener(Mojo.Event.deactivate, 
  this._onCardDeactivateHandler, false);

    this._isActivated = false;
    this._addressBar.stopObserving();
    this._addressBar.closeSearchResults();
};

Mojo.Format top
Article Title
Mojo.Format.formatChoice(value, choiceString, model)

Formats a string based on the data to be displayed.

Example usage:

    var files = 2185;
var model = { num: files };
print(Mojo.Format.formatChoice(files, "0#There are no files|1#There is one file|2<#There are #{num} files.", model);

Output:

    There are 2185 files.
Parameter Type Description
value Object Value used to select a choice from the choiceString.
choiceString String Concatenation of possible string choices.
model Object Object containing value.
Mojo.Format.formatDate(date, options)

Formats the provided date object based on the specified options. Returns String.

Parameter Type Description
date Object Date object to be formatted.
options String|Object

String: One of short, medium, long, full, default

Object: Date formatting options. See below.

options object properties:

Parameter Type Description
format String short, medium, long, full or default.  If only format specified, both date and time are returned.
date String short, medium, long, full or default. If only date specified, only date returned.
time String short, medium, long, full or default. If only time specified, only time returned.
countryCode String Two letter IETF/ISO 639 code for a country/region. Optional. Default is current device locale.
Mojo.Format.formatRelativeDate(date, options)

Formats the date object based on the specified parameters. Returns String containing the formatted date.

Parameter Type Description
date Date Date object to be formatted
options String|Object

String: Desired date format: short, medium, long, full, or default.  If date is in the last week, it returns the localized day.  If yesterday, today or tomorrow, it returns the localized strings for those days. Otherwise it returns the full date.

Object: See below.

options object properties:

Parameter Type Description
format String Desired date format: short, medium, long, full, or default.  If date is in the last week, it returns the localized day.  If yesterday, today or tomorrow, it returns the localized strings for those days. Otherwise it returns the full date.
countryCode String Two letter IETF/ISO 639 code for a country/region.
Mojo.Format.getFirstDayOfWeek(options)

Returns a zero-based index Number indicating what day is the first day of the country's or region's calendar week: Sunday: 0 Monday: 1 Tuesday: 2 etc.

Parameter Type Description
options Object Additional options for the method.  See below.

options object properties:

Properties Type Description
countryCode String Two letter IETF/ISO 639 code for country/region.  Optional.  Defaults to device's current locale.
Mojo.Format.isAmPmDefault(options)

Returns True if the current locale normally uses AM/PM as opposed to 24 hour time.

Parameter Type Description
options Object Additional options for the method.  See below.

options object properties:

Properties Type Description
countryCode String Two letter IETF/ISO 639 code for country/region.  Optional.  Defaults to device's current locale.
Mojo.Format.using12HrTime()

Returns True if the current app is using AM/PM instead of 24 hour time.  Otherwise, returns False.

Mojo.Format.formatCurrency(amount, options)

Formats the provided number as a locale-based currency string.  Returns String.

Parameter Type Description
amount Number Number to be formatted as currency.
options Number|Object

Number: Number of decimal places to include in the returned string.

Object: Additional formatting options.  See below.

options object properties:

Property Type Description
fractionDigits Number Number of places to include in the returned string.
countryCode String Two letter IETF/ISO 639 code for a country/region.  Optional.  Defaults to current device locale.
Mojo.Format.formatNumber(number, options)

Converts a number into a percent string using a locale-based format. Returns String.

Parameter Type Description
Number Number Number to format
options Number|Object

Number: Number of decimal places to include in the returned string.

Object: See below.

options object properties:

Properties Type Description
fractionDigits Number The number of decimal places to include in the returned string.
countryCode String Two letter IETF/ISO 639 code for country/region.  Optional.  Defaults to device's current locale.
Mojo.Format.formatPercent(percent, options)

Formats a number into a percent string using a locale-based format. Returns String.

Parameter Type Description
percent Number Percent number to be formatted.  Will not be multiplied by 100.
options Object See below.

options object properties:

Properties Type Description
countryCode String Two letter IETF/ISO 639 code for country/region.  Optional.  Defaults to device's current locale.
Mojo.Format.getCurrentTimeZone()

Returns a String indicating the current timezone of the device.

Mojo.Format.runTextIndexer(text)

Searches the specified text for URLs (web and mailto) and emoticons (if support is enabled) and returns a new String with those entities replaced by HTML links and images (respectively). 

Parameter Type Description
text String Text to transform to HTML
Mojo.Function top
Article Title
Mojo.Function.debounce(onCall, onTimeout, delay, optionalWindow)

Function to "debounce" multiple calls to a function, causing it to be called only once.  Can also be used to call a seconday function if the primary function has not been called after some specified delay.  Returns wrapped onCall function that can be called like the original function.  Upon calling the wrapped function, the onCall function is called immediately and the onTimeout function called if the wrapper is not called again within the specified delay.  Arguments passed to the onTimeout function are the same as those passed to the last call of the wrapped function.

Example usage:

// this.clearSearchString() will be called 1 second after the most recent call to this.delayedClear().

this.delayedClear = Mojo.Function.debounce(undefined, this.clearSearchString.bind(this), 1, this.controller.window);
Parameter Type Description
onCall Function Function called when the wrapper is invoked.  May be undefined.
onTimeout Function Function called if the wrapper has not been invoked after the specified delay elapses.
delay Integer Time in seconds before onTimeout is called.
optionalWindow String The window the delay time runs in.  Defaults to window.
Mojo.Function.Synchronize top
Article Title
Mojo.Function.Synchronize

Class used to ensure a set of functions are called simultaneously.  After creating a Mojo.Function.Synchronize object, the wrap() method can then be used to wrap callbacks to be synchronized before passing them to an asynchronous service.  The Synchronize object will "collect" the asynchronous callbacks until all have been received, then call the wrapped functions simultaneously.

Example usage:

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

curScene.aboutToActivate(synchronizer.wrap(doNothing));
beginOtherOperation(otherWrapper);
Parameter Type Description
inOptions Object Synchronization options.  See below.

inOptions object properties:

Property Type Description
syncCallback Function Called after all callbacks have been dispatched.  Passed a Boolean that is set to true if the synchronizer timed out. Optional.
timeout Number Number of seconds after which the synchronizer stops waiting, at which point all received wrapped functions and syncCallback are called.  Functions not yet returned are ignored but subsequent calls to them are immediately processed by the synchronize object.
Mojo.Function.Synchronize.wrap

Function to wrap a function within a Mojo.Function.Synchronize object so that it is called simultaneously with all other wrapped callbacks.  Returns wrapped Function that can be passed instead of the original callback function.

Parameter Type Description
callback Function Function to be wrapped and synchronized.

Example usage:

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

curScene.aboutToActivate(synchronizer.wrap(doNothing));
beginOtherOperation(otherWrapper);
Mojo.Log top
Article Title
Mojo.Log.addLoggingMethodsToPrototype(targetObject)

Function to add standard logging methods to an object's prototype.

Parameter Type Description
targetObject Object Object whose prototype should be extended with logging methods.

Example usage:

Adds logging methods to every scene controller:

    Mojo.Log.addLoggingMethodsToPrototype(Mojo.Controller.SceneController);

Allowing you to access logging from scene assistants:

    this.controller.info("Welcome to the dollhouse.");
Mojo.Log.error()

Function to write an error message to the log.

Parameters passed to a logging function are concatenated together using Array.join() with a single space separating each parameter.

Example usage:

    Mojo.Log.error("I have", 3, "eggs.");

Output:

    "I have 3 eggs."
Mojo.Log.info()

Function to write an informational message to the log.

Parameters passed to a logging function are concatenated together using Array.join() with a single space separating each parameter.

Example usage:

    Mojo.Log.info("I have", 3, "eggs.");

Output:

    "I have 3 eggs."
Mojo.Log.logException(e, msg)

Function to log an exception.

Parameter Type Description
e Object Exception to be logged
msg String Optional prefix for exception log message
Mojo.Log.logProperties(obj, name, includePrototype)

Function to log all properties of an object.  Outputs one property per line.

Parameter Type Description
obj Object Object whose properties should be output to the log.
name String Name to display for the object.
includePrototype Boolean True to include object properties inherited from a prototype.
Mojo.Log.propertiesAsString(targetObject, includePrototype)

Function to log a string containing all non-function properties of an object.

Parameter Type Description
targetObject Object Object whose non-function properties will be logged.
includePrototype Boolean True to include non-function properties inherited from the object's prototype.
Mojo.Log.warn()

Function to write a warning message to the log.

Parameters passed to a logging function are concatenated together using Array.join() with a single space separating each parameter.

Example usage:

    Mojo.Log.warn("I have", 3, "eggs.");

Output:

    "I have 3 eggs."
Mojo.Model top
Article Title
Mojo.Model.format(model, formatters, clone)

Function to format model properties.  Returns decorator Object containing formatted properties.

Parameter Type Description
model Object Object containing properties to be formatted.
formatters Object Object matching property names (keys) and formatter functions (values).  Formatted values have the text "formatted" appended to their names.  Unformatted values are retained in the object under their original names.
clone Object Object whose properties are copied to model decorator object before applying the formatter functions.  Optional.

Example usage:

var obj = Mojo.Model.format(this.controller.model, this.controller.attributes.formatters);
Mojo.Model.decorate(proto, clone)

Function to create a decorator object from a specified "original" object.  Properties can be added to or modified in the decorator object without affecting the original object.  Useful for widgets that need to add properties to the model in preparation for rendering. Returns Object.

Parameter Type Description
proto Object Object to decorate.  The returned decorator object's prototype field will refer to this object.
clone Object Object from which to clone properties into the new decorator object.

 

Mojo.Model.decrypt(key, data)

Function to decrypt a blowfish-encoded string.  Returns a base64 decoded String.

Parameter Type Description
key String Key to use to decrypt the data.
data String Data to be decrypted.

Example usage:

    var key = "sfhjasf7827387af9s7d8f";
var in_string = "This is a test string.";

var encrypted_string = Mojo.Model.encrypt( key, in_string );

var decrypted_string = Mojo.Model.decrypt( key, encrypted_string );
Mojo.Model.encrypt(key, data)

Function to encrypt a string using blowfish encryption.  Returns a base64-encoded String.

Parameter Type Description
key String Encryption key to be used to encrypt data.
data String Data to be encrypted.

Example usage:

    var key = "sfhjasf7827387af9s7d8f";
var in_string = "This is a test string.";

var encrypted_string = Mojo.Model.encrypt( key, in_string );

var decrypted_string = Mojo.Model.decrypt( key, encrypted_string );
Mojo.Model.Cookie top
Article Title
Mojo.Model.Cookie(cookieName, optionalDocument)

Creates a cookie object with the specified name.

Argument Type Description
cookieName String Name of the cookie
optionalDocument Object Document in which to store the cookie.  Defaults to current document.  (Optional)

Example usage:

//Get preferences cookie, or create it 
this.cookie = new Mojo.Model.Cookie("NewsPrefs"); 
var oldNewsPrefs = this.cookie.get(); 
if (oldNewsPrefs) { 
    if (oldNewsPrefs.newsVersionString == "1.0"){ 
            featureIndexFeed = oldNewsPrefs.featureIndexFeed; 
            featureFeedEnable = oldNewsPrefs.featureFeedEnable; 
            featureStoryInterval = oldNewsPrefs.featureStoryInterval; 
            feedUpdateInterval = oldNewsPrefs.feedUpdateInterval; 
            updateDialog = oldNewsPrefs.updateDialog; 
     } else { 
            this.cookie.put(){ 
               featureIndexFeed: featureIndexFeed, 
               featureFeedEnable: featureFeedEnable, 
               feedUpdateInterval: feedUpdateInterval, 
               featureStoryInterval: featureStoryInterval, 
               newsVersionString: newsVersionString 
            } 
    } 
} 
Mojo.Model.Cookie.get()

Returns the object stored in the cookie, or undefined if the cookie does not exist.

Example usage:

//Get preferences cookie, or create it 
this.cookie = new Mojo.Model.Cookie("NewsPrefs"); 
var oldNewsPrefs = this.cookie.get(); 
if (oldNewsPrefs) { 
    if (oldNewsPrefs.newsVersionString == "1.0"){ 
            featureIndexFeed = oldNewsPrefs.featureIndexFeed; 
            featureFeedEnable = oldNewsPrefs.featureFeedEnable; 
            featureStoryInterval = oldNewsPrefs.featureStoryInterval; 
            feedUpdateInterval = oldNewsPrefs.feedUpdateInterval; 
            updateDialog = oldNewsPrefs.updateDialog; 
     } else { 
            this.cookie.put(){ 
               featureIndexFeed: featureIndexFeed, 
               featureFeedEnable: featureFeedEnable, 
               feedUpdateInterval: feedUpdateInterval, 
               featureStoryInterval: featureStoryInterval, 
               newsVersionString: newsVersionString 
            } 
    } 
} 
Mojo.Model.Cookie.put(objectToStore, expirationDate)

Creates or updates the value of this cookie.

Argument Type Description
objectToStore Object Object to store in a cookie.  Must be encoded in JSON.
expirationDate Date Expiration date.  Will be deleted if set to the current time or earlier.  Optional.

Example usage:

  this.stageAssistant.cookie.put(        {
      featureIndexFeed: this.featureFeedListModel.value,
      featureFeedEnable: this.featureFeedToggleModel.value,
      feedUpdateInterval: this.feedIntervalModel.value,
      newsVersionString: newsVersionString,
      featureStoryInterval: featureStoryInterval
  });
Mojo.Model.Cookie.remove()

Deletes the cookie.

Example usage:

//Get preferences cookie, or create it 
this.cookie = new Mojo.Model.Cookie("NewsPrefs"); 
var oldNewsPrefs = this.cookie.get(); 
if (oldNewsPrefs) { 
    if (oldNewsPrefs.newsVersionString == "1.0"){ 
            featureIndexFeed = oldNewsPrefs.featureIndexFeed; 
            featureFeedEnable = oldNewsPrefs.featureFeedEnable; 
            featureStoryInterval = oldNewsPrefs.featureStoryInterval; 
            feedUpdateInterval = oldNewsPrefs.feedUpdateInterval; 
            updateDialog = oldNewsPrefs.updateDialog; 
     } else { 
            this.cookie.put(){ 
               featureIndexFeed: featureIndexFeed, 
               featureFeedEnable: featureFeedEnable, 
               feedUpdateInterval: feedUpdateInterval, 
               featureStoryInterval: featureStoryInterval, 
               newsVersionString: newsVersionString 
            } 
    } 
};
this.cookie.remove();
Mojo.PatternMatching top
Article Title
Mojo.PatternMatching.addContactMatchFormatting(input, filter, template)

 

Mojo.PatternMatching.getContactPatternMatch(filter)

 

Mojo.Require top
Article Title
Mojo.require(expression, message, messageProperties)

Writes an error to the log and throws an exception if expression doesn't evaluate to true.

Mojo.require and Mojo.assert methods are very similar.  The difference is that Mojo.require methods will throw an exception when their requirements aren't met, and are intended to be used in cases where the application cannot reasonably continue if the requirements aren't met.

Returns String containing the error message written to the log.

Parameter Type Description
expression Expression Expression that must evaluate to true.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

function(url) {
        Mojo.require(url, "Request requires a url");
        this.url = url;
    },
Mojo.requireArray(expectedArray, message, messageProperties)

Writes an error to the log and throws an exception if expectedArray fails the Prototype isArray method. Returns String containing the error message written to the log.

Parameter Type Description
expectedArray Object Object to be checked to be an array.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

  var names = this.testConstructorFunction[arrayName];
  if (names !== undefined) {
 	Mojo.requireArray(names, "testConstructorFunction." + arrayName +
              " must be undefined or an array.");
	this.functionsToRun = $A(names);
	return;
  }
Mojo.requireClass(object, constructorFunction, message, messageProperties)

Writes an error to the log and throws an exception if targetObject wasn't constructed by the passed in constructor function. Returns String containing the error message written to the log.

Parameter Type Description
object Object Object to check for constructing function.
constructorFunction Function Expected constructor function.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.requireDefined(value, message, messageProperties)

Writes an error to the log and throws an exception if value evaluates to undefined.  Returns String containing the error message written to the log.

Parameter Type Description
value Object Value that must not evaluate to undefined.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.Event.listen=function listen(target,type,handlerFunction,useCapture){
  Mojo.requireDefined(target,
    "Mojo.Event.listen: 'target' parameter must be defined.");
  Mojo.requireString(type,"Mojo.Event.listen: 'type' parameter must be a string.");
  Mojo.requireFunction(handlerFunction,
    "Mojo.Event.listen: 'handlerFunction' parameter must be a function.");
  target.addEventListener(type,handlerFunction,!!useCapture);
};
Mojo.requireElement(expectedElement, message, messageProperties)

Writes an error to the log and throws an exception if expectedElement fails the Prototype isElement method. Returns String containing the error message written to the log.

Parameter Type Description
expectedElement Object Object to be checked to be a element.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.View.makeFocusable = function(targetElement) {
    Mojo.requireElement(targetElement, "Mojo.View.makeFocusable requires an element.");
    targetElement.setAttribute("tabindex", "0");
};
Mojo.requireEqual(expected, actual, message, messageProperties)

Writes an error to the log and throws an exception if expected != actual. Returns String containing the error message written to the log.

Parameter Type Description
expected Anything The expected value.
actual Anything The actual value.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

    db.load(undefined, 0, 1, function(offset, array, totalCount){
    var readNote = array[0];
    Mojo.requireEqual(id, readNote.id);
    Mojo.requireEqual(1, totalCount);
    Mojo.requireFalse(readNote.text);
     
     // Save again all fields!
    note.text = '1';
    note.modifiedTimestamp = 2;
    note.position = 3;
    note.color = '4';
                    
    db.saveNote(note);
    db.loadNoteById(id, function(tx, readNote){
    Mojo.Log.logProperties(readNote);
    Mojo.requireEqual(id, readNote.id);
    Mojo.requireEqual('1', readNote.text);
    Mojo.requireEqual(2, readNote.modifiedTimestamp);
    Mojo.requireEqual(3, readNote.position);
    Mojo.requireEqual('4', readNote.color);
    // Done!
    recordResults(Mojo.Test.passed);
});
Mojo.requireFalse(expression, message, messageProperties)

Writes an error to the log and throws an exception if expression evaluates to true. Returns String containing the error message written to the log.

Parameter Type Description
expression Object Expression that must evaluate to false.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

    var details = this.detailsTable.get("5551212");
    Mojo.requireFalse(details, "Details must not be found");
Mojo.requireFunction(expectedFunction, message, messageProperties)

Writes an error to the log and throws an exception if expectedFunction fails the Prototype isFunction method. Returns String containing the error message written to the log.

Parameter Type Description
expectedFunction Object Object to be checked to be a function.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.Event.listen=function listen(target,type,handlerFunction,useCapture){
  Mojo.requireDefined(target,"Mojo.Event.listen: 'target' parameter must be defined.");
  Mojo.requireString(type,"Mojo.Event.listen: 'type' parameter must be a string.");
  Mojo.requireFunction(handlerFunction,
    "Mojo.Event.listen: 'handlerFunction' parameter must be a function.");
  target.addEventListener(type,handlerFunction,!!useCapture);
};
Mojo.requireMatch(regex, testValue, message, messageProperties)

Writes an error to the log and throws an exception if regex doesn't match testValue.

Writes an error to the log if expectedString fails the Prototype isString method. Returns String containing the error message written to the log.

Parameter Type Description
regex Regex Regular expression to match.
textValue String String to match against regex.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.requireNumber(expectedNumber, message, messageProperties)

Writes an error to the log and throws an exception if expectedNumber fails the Prototype isNumber method. Returns String containing the error message written to the log.

Parameter Type Description
expectedNumber Object Object to be checked to be a number.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

 

Mojo.requireProperty(properties)

Writes an error to the log and throws an exception if targetObject doesn't have the values for the property name or names passed and throws an exception.

Parameter Type Description
properties String|Array

String: Name of property to check.

Array: Array of strings containing names of properties to check.

 

Mojo.requireString(expectedString, message, messageProperties)

Writes an error to the log and throws an exception if expectedString fails the Prototype isString method. Returns String containing the error message written to the log.

Parameter Type Description
expectedString Object Object to be checked to be a string.
message String Custom message to use if the assertion fails. Message will be run through template evaluation against messageProperties so you can include details of the assertion failure in the message.
messageProperties Object Object containing values to use with template evaluation.

Example usage:

Mojo.Event.listen=function listen(target,type,handlerFunction,useCapture){
  Mojo.requireDefined(target,"Mojo.Event.listen: 'target' parameter must be defined.");
  Mojo.requireString(type,"Mojo.Event.listen: 'type' parameter must be a string.");
  Mojo.requireFunction(handlerFunction,
    "Mojo.Event.listen: 'handlerFunction' parameter must be a function.");
  target.addEventListener(type,handlerFunction,!!useCapture);
};
Mojo.Service top
Article Title
Mojo.Service.Request(url, options, requestOptions)

 

Mojo.Timing top
Article Title
Mojo.Timing.createTimingString(prefix, label)

Function to report all timings for a specified category prefix through Mojo.Log.info.

Parameter Type Description
prefix String Category prefix to identify which timings to report.
label String Label shown in output.
Mojo.Timing.reportSceneTiming(sceneName, sceneWindow)

Function to reports timings for scene push/pop operations, labeled with prefix 'scene#'.

Parameter Type Description
sceneName String Name of scene push/pop timing to report.
sceneWindow Object Window object containing scene.

Example usage:

        var timing = Mojo.Timing, that = this;
        timing.pause("scene#aboutToActivateLatency");
        timing.resume("scene#activate");
        this._active = true;
        timing.pause("scene#activate");
        var report = function(name) {
            timing.pause('scene#total');
            timing.reportSceneTiming(name, that.window);            
        };
        report.defer(this.sceneName);
Mojo.Timing.reportTiming(prefix, label)

Function to report all timings for a specified category prefix through Mojo.Log.info.

Parameter Type Description
prefix String Identifies which timings to report.
label String Label displayed in timing output.

Example usage:

    layoutCount = sceneWindow.layoutCount;
    Mojo.Log.info(Mojo.Timing.reportTiming('scene#', "scene '" + sceneName + "': layouts: " + layoutCount));
Mojo.Timing.reset(category)

Function to reset all timings for a specified category.

Parameter Type Description
category String Name of category whose timings will be reset.
Mojo.Timing.resetAllWithPrefix(prefix)

Function to reset all timers with the specified prefix.

Parameter Type Description
prefix String Category prefix.
Mojo.Timing.resetSceneTiming(sceneWindow)

Function to reset timings for scene push/pop operations.

Parameter Type Description
sceneWindow Object  

Example usage:

        Mojo.Timing.resetSceneTiming(this.window);
        Mojo.Timing.resume('scene#total');
Mojo.Timing.resume(category)

Function to begin or resume timing for a specified category.

Parameter Type Description
category String Category name.

Example usage:

        Mojo.Timing.resetSceneTiming(this.window);
        Mojo.Timing.resume('scene#total');
Mojo.Timing.get(category)

Function to get a performance timer for a specified category.  Creates the timer if it doesn't exist. Returns Object.

Parameter Type Description
category String Category of the timer.

Example usage:

    var timerForCategory = Mojo.Timing.get('category1');
    timerForCategory.resume();
Mojo.Timing.getCategoriesWithPrefix(prefix)

Function to get a list of category strings with a common prefix. Returns Array of Strings.

Parameter Type Description
previx String Common category prefix.

Example usage:

    var categories = Mojo.Timing.getCategoriesWithPrefix(prefix);
    var makeOneTiming = function(category) {
        var perfTimer = Mojo.Timing.get(category);
        return category.gsub(prefix, '') + ": " + 
           perfTimer.elapsedTime + "ms (" + perfTimer.timesRecorded + ")";
    };
    var timings = categories.collect(makeOneTiming);
Mojo.Timing.pause(category)

Function to pause timing for the specified category.

Parameter Type Description
category String Name of category to pause timing for.

Example usage:

Mojo.Timing.pause("scene#render");
Mojo.Timing.PerfTimer(label)

Function to create a reset performance timer with a particular label.

Parameter Type Description
label String Label that can be used to identify the timer.  Also used as the property name when added to the perfTimer's object.
Mojo.Timing.resetAll()

Function to reset all performance timers.

Mojo.Transition top
Article Title
Mojo.Transition.crossFade

Constant.

Specifies a quick and subtle cross-fade between scenes.

Example usage:

        var sController = this.controller.stageController;
        sController.popScene();
        sController.pushScene({name: "day", transition: Mojo.Transition.crossFade, 
               disableSceneScroller: true});
Mojo.Transition.defaultTransition

Constant.

Specifies the default transition to use when performing a default system defined transition.

Example usage:

this.controller.defaultTransition=Mojo.Transition.none;
Mojo.Transition.none

Constant.

Specifies that no graphical transition should be used when switching between scene.

Example usage:

this.controller.defaultTransition=Mojo.Transition.none;
Mojo.Transition.zoomFade

Constant.

Specifies a combination zoom and fade transition when a scene is pushed or popped.  This is the default scene transition.  Runs in reverse when scene is popped.

Example usage:

var transition = that.controller.prepareTransition(Mojo.Transition.zoomFade, true);
transition.run();
Mojo.View top
Article Title
Mojo.View.addTemplateLocation(basePath, localizedPath, viewFolderName)

Adds a pair of locations to be used for loading localized templates.  If a template is specified by full path and the base path is a prefix of the full path, the localized path for the correct locale will be searched for the template first.

Parameter Type Description
basePath String Path that contains templates.
localizedPath String Path that contains localized resources.
viewFolderName String Name of the folder inside the resources folder that contains the views.

Example usage:

    Mojo.View.addTemplateLocation("/templates/", "/templates/localized/, "views");

Mojo.View.addTouchFeedback(targetElement)

Adds touch feedback to a new element, removing touch feedback from any currently highlighted element.

Parameter Type Description
targetElement Element Element to display touch feedback.
Mojo.View.advanceFocus(containingElement, optionalSelection)

Advances the current text focus to the next focusable element in containingElement, or sets it to the first focusable element in the container if nothing in the container currently has focus.

Parameter Type Description
containingElement String Element in which to advance focus.
optionalSelection Element Element that will be used as the currently focused element if no element in containingElement currently has focus. Optional.

Example usage:

        Mojo.View.advanceFocus(this.controller.scene.sceneElement, this.inputArea);
Mojo.View.clearTouchFeedback(root)

 

Parameter Type Description
root Element Root element from which to clear touch feedback.
Mojo.View.convertToNode(htmlContent, targetDocument)

Converts the provided HTML content into nodes.  Returns the first Element node at the top level of the content.

Parameter Type Description
htmlContent Object HTML content to convert.
targetDocument Object  

Example usage:

content = Mojo.View.render({object: itemModel, template: itemModel.template});
node = Mojo.View.convertToNode(content, this.controller.document);
Mojo.View.convertToNodeList(htmlContent, targetDocument)

Converts the given html content into nodes and returns a nodelist. A shared rendering div is used for this conversion, so the caller needs to remove the nodes from their parent (the shared div) and should not keep a reference to the nodelist.

Parameter Type Description
htmlContent Object HTML content to convert.
targetDocument Object  

Example usage:

        // Set up spacer & content divs:
        spacers = Mojo.View.convertToNodeList("
               <div name='topSpacer' style='background-color:#e4e4e2;'></div>
               <div name='bottomSpacer' style='background-color:#e4e4e2;'></div>", 
               this.controller.document);
        this.topSpacer = spacers[0];
        this.bottomSpacer = spacers[1];
        Element.remove(this.topSpacer);
        Element.remove(this.bottomSpacer);
Mojo.View.getFocusedElement(containingElement)

Returns the currently focused element in containingElement, or null if there is no element that currently has focus.

Parameter Type Description
containingElement Element Element to search for a currently focused element.

Example usage:

//use this to blur the currently focused item
focusedElement = Mojo.View.getFocusedElement(this.controller.scene.sceneElement);
if (focusedElement) {
    focusedElement.blur();
}
Mojo.View.makeFocusable(targetElement)

Marks an element as focusable. Currently implemented by adding a tabindex attribute of value "0".

Parameter Type Description
targetElement Element Element to make focusable.

Example usage:

            var editor = this.controller.element;
            editor.setStyle(this.RICH_TEXT_STYLES);
            Mojo.View.makeFocusable(editor);
Mojo.View.makeNotFocusable(targetElement)

Marks an element as not focusable. Currently implemented by removing the tab index value.

Parameter Type Description
targetElement Element Element to make not focusable.

Example usage:

Mojo.View.makeNotFocusable(this.inputAreaDiv);
Mojo.View.requiresProperties(element, target, one)

Given a DOM element and a target object, hide the element if the value of any of the named properties are undefined or have a false value in target.

Parameter Type Description
element Element DOM element to hide.
target Object Object to check for property definitions.
one Object One or more property names.
Mojo.View.getFocusableList(containingElement)

Returns a list of focusable DOM elements in containingElement.

Parameter Type Description
containingElement String The DOM subtree to search for focusable elements.  containingElement is not included in the search.
Mojo.View.getScrollerForElement(targetElement)

Searches from targetElement up the DOM looking for a Scroller widget that contains targetElement.

Parameter Type Description
targetElement Element Element to find the scroller for.

Example usage:

var folderContainer = this.controller.get('account_folders_'+rowElement.id);
var scroller = Mojo.View.getScrollerForElement(folderContainer);
if (elementTop > viewPortMidway && scroller) {
   //Using setTimeout to give the animation time enough to 
   //give the div enough height to scroll to
   var scrollToPos = scroller.mojo.getScrollPosition().top - (elementTop - viewPortMidway);
   setTimeout(function() {scroller.mojo.scrollTo(undefined, scrollToPos, true);}, 200);
}
Mojo.View.removeTouchFeedback(targetElement)

Removes touch feedback from the specified element.

Parameter Type Description
targetElement Element Element from which to remove touch feedback.
Mojo.View.render(renderParams)

Create HTML markup from one or more objects.

Parameter Type Description
renderParams Object Rendering options.  See below.

renderParams object properties:

Property Type Description
object Object Object to use to resolve property references in the template.
collection Array List of objects to bind individually to a template to create a list.
attributes Object Additional object used to resolve property references when the property does not exist in object or the appropriate collection element.
formatters Object Hash of property names to formatter functions to be applied before rendering.  See Mojo.Model.format().
tempate String Partial or full path to the template.
separator String Partial or full path to template to use as a separator between individual list elements.

Example usage:

 html = Mojo.View.render(
  {
    object: {
      count: this.targetEventAttendees.attendees.size()
    }, 
    template: 'participants/participant-count'
  }
)
 this.controller.get('partv_count_div').update(html);

Example usage 2:

 var theDate = new Date(date);
            
 var y = Mojo.Format.formatDate(theDate, "yyyy");
 var m = Mojo.Format.formatDate(theDate, "MMM").toUpperCase();
 var d = Mojo.Format.formatDate(theDate, "dd");
 var button = Mojo.View.render({object: {label: $L("Date"), year: y, month: m, day: d},
                                template: "datetime/datePicker"});
 dateDiv.insert(button);
 var items = dateDiv.childElements();
 button = items[items.size() - 1];

Example usage 3:

 var content = Mojo.View.render({collection: songs,
             template: 'list/song', separator: 'list/separator''})
listElement.innerHTML = content;
Mojo.View.visible(element)

Function to check if a specified element and all of its ancestors are visible.  Returns Boolean.

Parameter Type Description
element Element Element to check for visibility.