springroll.Application Class
Application is the main entry point for using SpringRoll, creating
an application allows the creation of displays and adding of module
functionality (e.g. sound, captions, etc). All timing and asynchronous
events should be handled by the Application to control the play
and pause. Any update, Ticker-type functions, should use the Applications
update event.
var app = new Application();
Constructor
springroll.Application
Parameters:
-
[options]
Object
optional
The options for creating the application,
see springroll.ApplicationOptions
for the specific options
that can be overridden and set.
-
[init=null]
Function
optional
The callback when initialized
_doInit
()
protected
Initialize the application
_preInit
()
private
The internal initialization
_tick
()
private
_tick would be bound in _tickCallback
addDisplay
(
-
id
-
displayConstructor
-
[options]
)
Display
Add a display. If this is the first display added, then it will be stored as this.display.
Parameters:
-
id
String
The id of the canvas element, this will be used to grab the Display later
also the Display should be the one to called document.getElementById(id)
and not the application sinc we don't care about the DOMElement as this
point
-
displayConstructor
Function
The function to call to create the display instance
-
[options]
Object
optional
Optional Display specific options
Returns:
Display:
The created display.
addPreloadAssets
private
Add the preload assets to the list of assets to load
calculateDisplaySize
protected
Calculates the resizing of displays. By default, this limits the new size
to the initial aspect ratio of the primary display. Override this function
if you need variable aspect ratios.
Parameters:
-
size
Object
A size object containing the width and height of the resized container.
The size parameter is also the output of the function, so the size
properties are edited in place.
-
width
Int
The width of the resized container.
-
height
Int
The height of the resized container.
destroy
()
Destroys the application and all active displays and plugins
endGame
(
-
[exitType='game_completed']
)
Manually close the application, this can happen when playing through once
Parameters:
-
[exitType='game_completed']
String
optional
getCache
| Null
Get an asset from the cache by ID
Returns:
| Null:
The cached object or null if empty
getDisplay
Display
Gets a specific renderer by the canvas id.
Returns:
Display:
The requested display.
getDisplays
Array
deprecated
Parameters:
-
[each]
Function
optional
Iterator function, param is each method
Returns:
Array:
The collection of displays
has
Boolean
Checks if the EventDispatcher has a specific listener or any listener for a given event.
Parameters:
-
name
String
The name of the single event type to check for
-
[callback]
Function
optional
The listener function to check for. If omitted, checks for any listener.
Returns:
Boolean:
If the EventDispatcher has the specified listener.
internalPaused
protected
Handle the internal pause of the application
Parameters:
-
paused
Boolean
If the application should be paused or not
load
Load a single file with options.
Parameters:
-
asset
Object
The file resource to load
-
src
String
-
[cache=false]
Boolean
optional
If the result should be cached for later
-
[complete=null]
Function
optional
-
[progress=null]
Function
optional
Callback on load progress,
has a parameter which is the percentage loaded from 0 to 1.
-
[data]
optional
Additional data to attach to load is
accessible in the loader's result.
-
[complete]
Function
optional
The completed callback with a single
parameter which is a result object. will
only use if asset.complete
is undefined.
load
(
-
source
-
complete
-
[progress]
-
[cache=false]
-
[data]
)
Simple load of a single file.
Parameters:
-
source
String
-
complete
Function
The completed callback with a single
parameters result object.
-
[progress]
Function
optional
Update callback, return 0-1
-
[cache=false]
Boolean
optional
Save to the asset cache after load
-
[data]
optional
The data to attach to load item
load
Load a single custom asset with options.
Parameters:
-
asset
Object
The single asset resource to load, properties
will depend on the type of asset loading.
-
[complete=null]
Function
optional
-
[id=null]
String
optional
The ID to attach to this asset
-
[cache=false]
Boolean
optional
If the result should be cached for later
-
[complete]
Function
optional
The completed callback with a single
parameters which is a result object. will
only use if asset.complete
is undefined.
load
Load a list of multiple assets and return array of result objects.
Parameters:
-
assets
Array
The list of assets.
If each object has a id
the result will be a mapped object.
-
[options]
Function | Object
optional
Callback where the only parameter is the
collection or map of the results, or the collection of load options.
-
[complete=null]
Function
optional
The complete callback if using load options.
-
[taskDone=null]
Function
optional
The callback when a single item is finished.
-
[progress=null]
Function
optional
Callback percentage updates
-
[cacheAll=false]
Boolean
optional
If tasks should be cached
-
[startAll=true]
Boolean
optional
If tasks should be run in parallel
-
[type]
String
optional
The default asset type of load, gets attached to each asset
load
Load a map of multiple assets and return mapped result objects.
Parameters:
-
assets
Object
-
[options]
Function | Object
optional
Callback where the only parameter is the
map of the results by ID, or the collection of load options.
-
[complete=null]
Function
optional
The complete callback if using load options.
-
[taskDone=null]
Function
optional
The callback when a single item is finished.
-
[progress=null]
Function
optional
Callback percentage updates
-
[cacheAll=false]
Boolean
optional
If tasks should be cached
-
[startAll=true]
Boolean
optional
If tasks should be run in parallel
-
[type]
String
optional
The default asset type of load, gets attached to each asset
off
EventDispatcher
Remove the event listener
Parameters:
-
name
String*
The type of event string separated by spaces, if no name is specifed remove all listeners.
-
callback
Function | Array*
The listener function or collection of callback functions
Returns:
EventDispatcher:
Return this EventDispatcher for chaining calls.
on
(
-
name
-
callback
-
[priority=0]
)
EventDispatcher
Add an event listener. The parameters for the listener functions depend on the event.
Parameters:
-
name
String | Object
The type of event (can be multiple events separated by spaces),
or a map of events to handlers
-
callback
Function | Array*
The callback function when event is fired or an array of callbacks.
-
[priority=0]
Int
optional
The priority of the event listener. Higher numbers are handled first.
Returns:
EventDispatcher:
Return this EventDispatcher for chaining calls.
onAnimatorHint
private
Handle the animator event
onCaptionsMuted
private
Handler when the captions are muted
onCaptionsStyles
private
The captions style is being set
once
(
-
name
-
callback
-
[priority=0]
)
EventDispatcher
Add an event listener but only handle it one time.
Parameters:
-
name
String | Object
The type of event (can be multiple events separated by spaces),
or a map of events to handlers
-
callback
Function | Array*
The callback function when event is fired or an array of callbacks.
-
[priority=0]
Int
optional
The priority of the event listener. Higher numbers are handled first.
Returns:
EventDispatcher:
Return this EventDispatcher for chaining calls.
onClose
()
private
Game container requests closing the application
onConfigLoaded
private
Callback when the config is loaded
Parameters:
-
config
Object
The Loader result from the load
-
asset
Object
-
assets
Array
The array to add new load tasks to
onContextMuted
private
Handler when the context is muted
Parameters:
-
context
String
The name of the sound context
-
e
Event
onHidden
()
private
Private listener for when the page is hidden.
onLoadComplete
private
Callback when tasks are completed
Parameters:
-
done
Function
-
results
Array
The collection of final LoaderResult objects
onManifestsLoaded
private
Callback to when manifests have been loaded
Parameters:
-
tasks
Array
The collection of preload tasks
onPause
private
When the container pauses the application
onPlayOptions
private
Handler when a application enters single play mode
onPluginProgress
private
Progress handler for the plugin load
Parameters:
-
progress
Number
Plugins preloaded amount from 0 - 1
onProgress
private
Callback when progress is finished
Parameters:
-
progress
Number
The amount loaded from 0 to 1
onSinglePlay
private
Handler when a application enters single play mode
onSoundMuted
private
Handler when the sound is muted
onVisible
()
private
Private listener for when the page is shown.
onWindowError
private
Handle the window uncaught errors with the container
onWindowResize
()
protected
Handle the window resize events
onWindowUnload
()
private
Handler for when a window is unloaded
removeDisplay
Removes and destroys a display
Parameters:
-
id
String
The Display's id (also the canvas ID)
setInterval
(
-
callback
-
delay
-
[useFrames=false]
)
springroll.DelayedCall
Works just like window.setInterval
but respects the pause
state of the Application.
Parameters:
-
callback
Function
The callback function, passes one argument which is the DelayedCall instance
-
delay
Int
The time in milliseconds or the number of frames (useFrames must be true)
-
[useFrames=false]
Boolean
optional
If the delay is frames (true) or millseconds (false)
setTargetedTimeout
private
Makes a setTimeout with a time based on _msPerFrame and the amount of time spent in the
current tick.
Parameters:
-
callback
Function
The tick function to call.
-
timeInFrame=0
Int
The amount of time spent in the current tick in milliseconds.
setTimeout
(
-
callback
-
delay
-
[useFrames=false]
-
[autoDestroy=true]
)
springroll.DelayedCall
Works just like window.setTimeout
but respects the pause
state of the Application.
Parameters:
-
callback
Function
The callback function, passes one argument which is the DelayedCall instance
-
delay
Int
The time in milliseconds or the number of frames (useFrames must be true)
-
[useFrames=false]
Boolean
optional
If the delay is frames (true) or millseconds (false)
-
[autoDestroy=true]
type
optional
If the DelayedCall object should be destroyed after completing
singlePlayEnd
()
Boolean
When a application is in singlePlay mode it will end.
It's unnecessary to check if (this.singlePlay)
just
call the method and it will end the application if it can.
toString
()
String
The toString debugging method
Returns:
String:
The reprsentation of this class
trigger
Dispatch an event
triggerResize
()
Fire a resize event with the current width and height of the display
type
String
private
Return type of the value.
unload
Unload an asset or list of assets.
Parameters:
-
assets
Array | String
The collection of asset ids or
single asset id. As an array, it can be a manifest
with objects that contain an ID, or an array of multiple strings.
unloadAll
()
Unload all assets from the assets cache
_destroyed
Boolean
protected
If the dispatcher is destroyed
_displays
Array
private
The collection of displays
_displaysMap
Object
private
The displays by canvas id
_enabled
Boolean
private
If the current application is enabled
_framerate
DOMElement
private
_lastFrameTime
Int
private
The number of ms since the last frame update
_listeners
Object
private
The collection of listeners
_manifests
Object
private
The collection of loading assets by state
_maxHeight
Number
private
The maximum height of the primary display, compared to the original width.
_maxWidth
Number
private
The maximum width of the primary display, compared to the original height.
_msPerFrame
Int
private
The number of milliseconds per frame
_music
String
private
The current music alias playing
_musicInstance
SoundInstance
private
The current music SoundInstance playing
_numLoaded
Int
private
The total number of assets loaded
_originalHeight
Int
private
The original height of the primary display, used to calculate the aspect ratio.
_originalWidth
Int
private
The original width of the primary display, used to calculate the aspect ratio.
_paused
Boolean
private
If the current application is paused
_plugins
Array
private
static
The collection of function references to call when initializing the application
these are registered by external modules.
_progress
Number
private
The current combined progress with plugin and asset load
Default: -1
_resizeElement
DOMElement | Window | Null
private
Dom element (or the window) to attach resize listeners and read the size from
Default: null
_resizeHelper
Object
private
A helper object to avoid object creation each resize event.
_tickCallback
Function
private
The bound callback for listening to tick events
_tickId
Number
private
The id of the active requestAnimationFrame or setTimeout call.
_time
Number
private
Keep track of total time elapsed to feed to the Ticker
Default: 0
_total
Int
private
The total assets to preload
_useRAF
Bool
private
If requestionAnimationFrame should be used
Default: false
_visibility
springroll.PageVisibility
private
Handles the page visiblity changes automatically
to pause and resume the application
autoPaused
Boolean
protected
Setter for if the application is being automatically paused,
usually by the PageVisibility plugin or the ContainerClient plugin.
config
Object
The game configuration loaded from and external JSON file
container
Bellhop
Send a message to let the site know that this has
been loaded, if the site is there
destroyed
Boolean
If the dispatcher is destroyed
display
Display
public
Primary renderer for the application, for simply accessing
Application.instance.display.stage;
The first display added becomes the primary display automatically.
enabled
Boolean
Enables at the application level which enables
and disables all the displays.
Default: true
hasTouch
Boolean
If the current brower has touch input available
init
Function
Override this to do post constructor initialization
instance
Application
public
static
Get the singleton instance of the application
isAndroid
Boolean
If the current brower is Android
isIOS
Boolean
If the current brower is iOS
manifests
Object
Read-only getter to return _manifests
music
String
Get or set the current music alias to play
Default: null
musicInstance
SoundInstance
The SoundInstance for the current music, for adjusting volume.
name
String
The name of the game, useful for debugging purposes
Default: ""
options
springroll.ApplicationOptions
Initialization options/query string parameters, these properties are read-only
Application properties like raf, fps, don't have any affect on the options object.
options.audioPlugins
Array
The preferred order of SoundJS audio plugins to use.
Default: [WebAudioPlugin,FlashAudioPlugin]
options.audioTypes
Array
The order in which file types are
preferred, where "ogg" becomes a ".ogg"
extension on all sound file urls.
Default: ['ogg','mp3']
options.autoPause
Boolean
The application pauses automatically when the window loses focus.
Default: true
options.basePath
String
The optional file path to prefix to any relative file
requests. This is a great way to load all load requests
with a CDN path.
options.cacheBust
Boolean
Override the end-user browser cache by adding
"?cb=" to the end of each file path requested. Use
for development, debugging only!
Default: DEBUG
options.canvasId
String
The default display DOM ID name
options.captions
DOMElement | String | createjs.Text | PIXI.Text | PIXI.BitmapText
The captions text field object to use for the
VOPlayer captions object.
Default: 'captions'
options.captionsPath
String
The path to the captions file to preload.
Default: null
options.configPath
String
The path to the config file to load
Default: null
options.debug
Boolean
Enable the Debug class. After initialization, this
is a pass-through to Debug.enabled.
Default: true
options.debugRemote
String
The host computer for remote debugging, the debug
module must be included to use this feature. Can be an
IP address or host name. After initialization, setting
this will still connect or disconect Debug for remote
debugging. This is a write-only property.
options.defaultAssetType
String
Different displays offer flavors of the same asset definition.
Instead of repeatedly defining the asset type property,
it's possible to define a global default. If PIXI
is your default display "pixi" is recommended as a value.
If EaselJS is your default display "easeljs" is recommended.
options.display
Function
The name of the class to automatically instantiate as the
display (e.g. springroll.PixiDisplay
)
options.displayOptions
Object
Display specific setup options
options.enableHiDPI
Boolean
Whether to account for devicePixelRatio when rendering game
Default: false
options.forceFlashAudio
Boolean
For the Sound class to use the Flash plugin shim
Default: false
options.forceNativeAudio
Boolean
For the Sound class to use Native Audio Plugin if Cordova is detected. Only applicable to games that require native audio.
If set to true, use Native Audio in Cordova if the plugin is available.
If set to false, then Sound will fall back to the standard plugins as set either by plugin options or in sound class.
Default: false
options.forceTouch
Boolean
Manually override the check for hasTouch (unminifed library version only)
Default: false
options.fps
Int
The framerate to use for rendering the stage
Default: 60
options.framerate
String | DOMElement
options.keepFocus
Boolean
This option tells the container to always keep focus on the iframe even
when the focus is lost. This is useful mostly if your Application
requires keyboard input.
options.language
String
Force a specific language
Default: null
options.languagesPath
String
The path to the languages configuration file
Default: null
options.manifestsPath
String
The path to the concatinated FLA exported manifests. It's useful
to load all the manifests at once. This JSON object contains a
dictionary of state alias and contains an array of manifest assets
(e.g. {"id": "PlayButton", "src": "assets/images/button.png"}
.
Set to null and no manifest will be auto-loaded.
Default: null
options.maxHeight
Int
If doing uniform resizing, optional parameter to add
a maximum height relative to the original width. This
allows for "title-safe" responsiveness. Must be greater
than the original height of the canvas.
options.maxWidth
Int
If doing uniform resizing, optional parameter to add
a maximum width relative to the original height. This
allows for "title-safe" responsiveness. Must be greater
than the original width of the canvas.
options.minLogLevel
Int
Minimum log level from 0 to 4
Default: 0
options.mute
Boolean
Set the initial mute state of the all the audio
(unminifed library version only)
Default: false
options.name
String
The name of the application
Default: ''
options.preload
String | Array | Object
The collection of assets to preload, can be individual
URLs or objects with keys src
, complete
, progress
, etc.
Default: []
options.raf
Boolean
Use Request Animation Frame API
Default: true
options.resizeElement
DOMElement | String
The element that the canvas is resized to fit.
Default: 'frame'
options.responsive
Boolean
If responsive is true, the width and height properties
are adjusted on the <canvas>
element. It's assumed that
responsive applications will adjust their own elements.
If responsive is false then the style properties are changed.
Default: false
options.state
Boolean
The initial state to go to when everything is finished
Default: null
options.swfPath
String
The relative location to the FlashPlugin swf for SoundJS
Default: 'assets/swfs/'
options.transition
createjs.MovieClip | PIXI.Spine
The animation to use for the StateManager
options.transitionSounds
Object
The transition sounds to use for the state transition
options.transitionSounds.in
Object
The transition in sound alias or sound object
Default: null
options.transitionSounds.out
Object
The transition out sound alias or sound object
Default: null
options.updateTween
Boolean
If using TweenJS, the Application will update the Tween itself.
Default: true
options.useQueryString
Boolean
Use the query string parameters for options overrides
Default: false
options.version
String
The current version number for your application. This
number will automatically be appended to all file
requests. For instance, if the version is "0.0.1" all
file requests will be appended with "?v=0.0.1"
options.versionsFile
String
Path to a text file which contains explicit version
numbers for each asset. This is useful for controlling
the live browser cache. For instance, this text file
would have an asset on each line followed by a number:
assets/config/config.json 2
would load
assets/config/config.json?v=2
paused
Boolean
Manual pause for the entire application, this suspends
anything driving the the application update events. Include
Animator, Captions, Sound and other media playback.
playOptions
Object
The optional play options to use if the application is played in "single play"
mode. These options are passed from the application container to specify
options that are used for this single play session. For instance,
if you want the single play to focus on a certain level or curriculum
such as { "shape": "square" }
realHeight
Int
The current height of the application, in real point values
realWidth
Int
The current width of the application, in real point values
singlePlay
Boolean
The default play-mode for the application is continuous, if the application is
running as part of a sequence is it considered in "single play" mode
and the application will therefore close itself.
Default: false
sound
springroll.Sound
The global player for all audio, also accessible through singleton
states
Object
The collection of states where the key is the state alias and value is the state display object
Default: null
userData
springroll.UserData
The API for saving user data, default is to save
data to the container, if not connected, it will
save user data to local cookies
version
String
static
The current version of the library
afterInit
Fired when initialization of the application is done
beforeInit
Fired when before initialization of the application
configLoaded
The config has finished loading, in case you want to
add additional tasks to the manager after this.
Event Payload:
-
config
Object
The JSON object for config
-
assets
Array
Container to add additional assets to
destroy
Fired when the application is destroyed
displayRemoved
When a display is removed.
init
Fired when initialization of the application is ready
loaded
The game has finished loading
loading
The game has started loading
Event Payload:
-
assets
Array
The list of tasks to preload
manifestLoaded
Event when the manifest is finished loading
Event Payload:
-
assets
Array
The object of additional assets to load
pause
Fired when the pause state is toggled
Event Payload:
-
paused
Boolean
If the application is now paused
paused
Fired when the application becomes paused
pluginProgress
The handler for the plugin progress
progress
The amount of progress of the preload from 0 to 1
resize
Fired when a resize is called
Event Payload:
-
width
Int
The width of the resize element
-
height
Int
The height of the resize element
resumed
Fired when the application resumes from a paused state
soundReady
The sound is ready to use
stateAdded
Fired when an event has been added
update
Fired when an update is called, every frame update
Event Payload:
-
elasped
Int
The number of milliseconds since the last frame update