YUI Class
The YUI global namespace object. This is the constructor for all YUI instances.
This is a self-instantiable factory function, meaning you don't need to precede
it with the new
operator. You can invoke it directly like this:
YUI().use('*', function (Y) {
// Y is a new YUI instance.
});
But it also works like this:
var Y = YUI();
The YUI
constructor accepts an optional config object, like this:
YUI({
debug: true,
combine: false
}).use('node', function (Y) {
// Y.Node is ready to use.
});
See the API docs for the Config class for the complete list of supported configuration properties accepted by the YUI constuctor.
If a global YUI
object is already defined, the existing YUI object will not be
overwritten, to ensure that defined namespaces are preserved.
Each YUI instance has full custom event support, but only if the event system is available.
Constructor
Item Index
Methods
- _afterConfig
- _aggregateGroups
- _attach
- _buildCombo
- _config
- _customResolve
- _delayCallback
- _getFullType
- _getLoadHook
- _getType
- _hasPotentialSubscribers
- _init
- _monitor
- _notify
- _parseType
- _pathogenEncodeComboSources
- _publish
- _setup
- _sortAggregatedGroups
- _use
- add
- addTarget
- after
- aggregate
- all
- applyConfig static
- applyConfig
- applyTo
- assert static
- augment
- batch
- before
- bind
- bubble
- cached
- clone
- delegate
- destroy
- detach
- detachAll
- dispatch
- dump
- each
- error
- extend
- fail static
- fire
- getEvent
- getLocation
- getTargets
- guid
- header static
- instanceOf
- io static
- jsonp static
- later
- log
- merge
- message
- mix
- namespace
- on
- once
- onceAfter
- one
- parseType
- publish
- rbind
- removeTarget
- require
- setLoadHook static
- some
- soon
- stamp
- subscribe deprecated
- throttle
- unsubscribe deprecated
- unsubscribeAll deprecated
- use
- when
Properties
- Global
- GlobalConfig static
- meta
- version
- YUI_config
Methods
_afterConfig
()
private
This method is called after all other configuration has been applied to the YUI instance.
_aggregateGroups
-
modules
Aggregate modules into groups with unique keys. The key is "$name+$version" for core and gallery groups, and just "$root" for all other groups.
Parameters:
-
modules
ArrayA list of module meta.
Returns:
Aggregated groups of module meta.
_attach
-
r
-
[moot=false]
Executes the callback function associated with each required module, attaching the module to this YUI instance.
_buildCombo
-
groups
-
comboBase
-
comboTail
Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now.
Parameters:
Returns:
A combo url.
_config
-
o
Old way to apply a config to this instance (calls applyConfig
under the
hood).
Parameters:
-
o
ObjectThe config to apply
_customResolve
-
modules
-
type
Build each combo url from the bottom up. There's probably room for optimization here, but let's keep it simple for now.
Returns:
Combo url.
_delayCallback
-
cb
-
until
Delays the use
callback until another event has taken place such as
window.onload
, domready
, contentready
, or available
.
Parameters:
Returns:
_getFullType
-
type
Returns the fully qualified type, given a short type string. That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix.
NOTE: This method, unlike _getType, does no checking of the value passed in, and is designed to be used with the low level _publish() method, for critical path implementations which need to fast-track publish for performance reasons.
Parameters:
-
type
StringThe short type to prefix
Returns:
The prefixed type, if a prefix is set, otherwise the type passed in
_getLoadHook
-
data
-
path
Load hook for Y.Get.script
in Node.js, see YUI.setLoadHook
_getType
()
private
If the instance has a prefix attribute and the event type is not prefixed, the instance prefix is applied to the supplied type.
_hasPotentialSubscribers
-
fullType
Parameters:
-
fullType
StringThe fully prefixed type name
Returns:
Whether the event has potential subscribers or not
_init
()
private
Initializes this YUI instance.
_monitor
-
what
-
eventType
-
o
This is the entry point for the event monitoring system. You can monitor 'attach', 'detach', 'fire', and 'publish'. When configured, these events generate an event. click -> click_attach, click_detach, click_publish -- these can be subscribed to like other events to monitor the event system. Inividual published events can have monitoring turned on or off (publish can't be turned off before it it published) by setting the events 'monitor' config.
Parameters:
-
what
String'attach', 'detach', 'fire', or 'publish'
-
eventType
String | CustomEventThe prefixed name of the event being monitored, or the CustomEvent object.
-
o
ObjectInformation about the event interaction, such as fire() args, subscription category, publish config
_notify
-
callback
-
response
-
args
Handles Loader notifications about attachment/load errors.
_parseType
()
private
Returns an array with the detach key (if provided), and the prefixed event name from _getType Y.on('detachcategory| menu:click', fn)
_pathogenEncodeComboSources
-
resolved
Encodes combo urls based on modules and appends them to an object hash of arrays from loader.resolve
.
Parameters:
-
resolved
ObjectThe object hash of arrays in which to attach the encoded combo sources.
Returns:
Object
_publish
-
fullType
-
etOpts
-
ceOpts
The low level event publish implementation. It expects all the massaging to have been done
outside of this method. e.g. the type
to fullType
conversion. It's designed to be a fast
path publish, which can be used by critical code paths to improve performance.
Parameters:
Returns:
The published event. If called without etOpts
or ceOpts
, this will
be the default CustomEvent
instance, and can be configured independently.
_setup
()
private
Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created.
_sortAggregatedGroups
-
groups
Sort the aggregated groups, and the modules within them. Minimizes cache misses in Yahoo's infrastructure by encoding predictable combo urls across browsers since iterating over an object does not guarantee order.
Parameters:
-
groups
ObjectAggregated groups.
Returns:
Sorted groups.
_use
-
args
-
[callback]
Called from the use
method queue to ensure that only one set of loading
logic is performed at a time.
add
-
name
-
fn
-
version
-
[details]
Registers a YUI module and makes it available for use in a YUI().use()
call or
as a dependency for other modules.
The easiest way to create a first-class YUI module is to use Shifter, the YUI component build tool.
Shifter will automatically wrap your module code in a YUI.add()
call along
with any configuration info required for the module.
Parameters:
-
name
StringModule name.
-
fn
FunctionFunction containing module code. This function will be executed whenever the module is attached to a specific YUI instance.
-
version
StringModule version number. This is currently used only for informational purposes, and is not used internally by YUI.
-
[details]
Object optionalModule config.
-
[requires]
Array optionalArray of other module names that must be attached before this module can be attached.
-
[optional]
Array optionalArray of optional module names that should be attached before this module is attached if they've already been loaded. If the
loadOptional
YUI option istrue
, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. -
[use]
Array optionalArray of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules.
-
Returns:
This YUI instance.
Example:
YUI.add('davglass', function (Y) {
Y.davglass = function () {
Y.log('Dav was here!');
};
}, '3.4.0', {
requires: ['harley-davidson', 'mt-dew']
});
addTarget
-
o
Registers another EventTarget as a bubble target. Bubble order is determined by the order registered. Multiple targets can be specified.
Events can only bubble if emitFacade is true.
Included in the event-custom-complex submodule.
Parameters:
-
o
EventTargetthe target to add
after
-
type
-
fn
-
[context]
-
[args*]
Like on()
, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, after()
subscribers are executed after the event's
defaultFn
unless e.preventDefault()
was called from an on()
subscriber.
See the on()
method for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See Y.Do.after
for that signature.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
aggregate
-
receiver
-
supplier
-
[overwrite=false]
-
[whitelist]
Copies object properties from the supplier to the receiver. If the target has the property, and the property is an object, the target object will be augmented with the supplier's value.
Parameters:
-
receiver
ObjectObject to receive the augmentation.
-
supplier
ObjectObject that supplies the properties with which to augment the receiver.
-
[overwrite=false]
Boolean optionalIf
true
, properties already on the receiver will be overwritten if found on the supplier. -
[whitelist]
String[] optionalWhitelist. If supplied, only properties in this list will be applied to the receiver.
Returns:
Augmented object.
all
-
selector
Retrieves a NodeList based on the given CSS selector.
Parameters:
-
selector
StringThe CSS selector to test against.
Returns:
A NodeList instance for the matching HTMLCollection/Array.
applyConfig
-
o
Applies a configuration to all YUI instances in this execution context.
The main use case for this method is in "mashups" where several third-party
scripts need to write to a global YUI config, but cannot share a single
centrally-managed config object. This way they can all call
YUI.applyConfig({})
instead of overwriting the single global config.
Parameters:
-
o
ObjectConfiguration object to apply.
Example:
YUI.applyConfig({
modules: {
davglass: {
fullpath: './davglass.js'
}
}
});
YUI.applyConfig({
modules: {
foo: {
fullpath: './foo.js'
}
}
});
YUI().use('davglass', function (Y) {
// Module davglass will be available here.
});
applyConfig
-
o
Applies a new configuration object to the config of this YUI instance. This
will merge new group/module definitions, and will also update the loader
cache if necessary. Updating Y.config
directly will not update the cache.
Parameters:
-
o
Objectthe configuration object.
applyTo
-
id
-
method
-
args
Executes the named method on the specified YUI instance if that method is whitelisted.
Parameters:
Returns:
Return value from the applied method, or null
if the
specified instance was not found or the method was not whitelisted.
assert
-
condition
-
message
Asserts that a given condition is true. If not, then a Y.Assert.Error object is thrown and the test fails.
augment
-
receiver
-
supplier
-
[overwrite=false]
-
[whitelist]
-
[args]
Augments the receiver with prototype properties from the supplier. The receiver may be a constructor function or an object. The supplier must be a constructor function.
If the receiver is an object, then the supplier constructor will be called
immediately after receiver is augmented, with receiver as the this
object.
If the receiver is a constructor function, then all prototype methods of supplier that are copied to receiver will be sequestered, and the supplier constructor will not be called immediately. The first time any sequestered method is called on the receiver's prototype, all sequestered methods will be immediately copied to the receiver's prototype, the supplier's constructor will be executed, and finally the newly unsequestered method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the supplier's constructor.
Parameters:
-
receiver
Function | ObjectObject or function to be augmented.
-
supplier
FunctionFunction that supplies the prototype properties with which to augment the receiver.
-
[overwrite=false]
Boolean optionalIf
true
, properties already on the receiver will be overwritten if found on the supplier's prototype. -
[whitelist]
String[] optionalAn array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored.
-
[args]
Array | Any optionalArgument or array of arguments to pass to the supplier's constructor when initializing.
Returns:
Augmented object.
batch
-
operation
Returns a new promise that will be resolved when all operations have completed.
Takes both any numer of values as arguments. If an argument is a not a promise,
it will be wrapped in a new promise, same as in Y.when()
.
Parameters:
-
operation
Any multipleAny number of Y.Promise objects or regular JS values
Returns:
Promise to be fulfilled when all provided promises are resolved
before
()
Executes the callback before a DOM event, custom event or method. If the first argument is a function, it is assumed the target is a method. For DOM and custom events, this is an alias for Y.on.
For DOM and custom events: type, callback, context, 0-n arguments
For methods: callback, object (method host), methodName, context, 0-n arguments
Returns:
detach handle
bind
-
f
-
c
-
args
Returns a function that will execute the supplied function in the supplied object's context, optionally adding any additional supplied parameters to the beginning of the arguments collection the supplied to the function.
Parameters:
Returns:
the wrapped function.
bubble
-
evt
Propagate an event. Requires the event-custom-complex module.
Parameters:
-
evt
CustomEventthe custom event to propagate
Returns:
the aggregated return value from Event.Custom.fire
cached
-
source
-
[cache={}]
-
[refetch]
Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called.
Calling this function again with the same arguments will return the cached value rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful toString()
method may result in unexpected caching behavior. For
example, the objects {}
and {foo: 'bar'}
would both be converted to the
string [object Object]
when used as a cache key.
Parameters:
-
source
FunctionThe function to memoize.
-
[cache={}]
Object optionalObject in which to store cached values. You may seed this object with pre-existing cached values if desired.
-
[refetch]
Any optionalIf supplied, this value is compared with the cached value using a
==
comparison. If the values are equal, the wrapped function is executed again even though a cached value exists.
Returns:
Wrapped function.
clone
-
o
-
safe
-
f
-
c
-
owner
-
cloned
Deep object/array copy. Function clones are actually wrappers around the original function. Array-like objects are treated as arrays. Primitives are returned untouched. Optionally, a function can be provided to handle other data types, filter keys, validate values, etc.
Note: Cloning a non-trivial object is a reasonably heavy operation, due to the need to recursively iterate down non-primitive properties. Clone should be used only when a deep clone down to leaf level properties is explicitly required. This method will also
In many cases (for example, when trying to isolate objects used as hashes for
configuration properties), a shallow copy, using Y.merge()
is normally
sufficient. If more than one level of isolation is required, Y.merge()
can be
used selectively at each level which needs to be isolated from the original
without going all the way to leaf properties.
Parameters:
-
o
Objectwhat to clone.
-
safe
Booleanif true, objects will not have prototype items from the source. If false, they will. In this case, the original is initially protected, but the clone is not completely immune from changes to the source object prototype. Also, cloned prototype items that are deleted from the clone will result in the value of the source prototype being exposed. If operating on a non-safe clone, items should be nulled out rather than deleted.
-
f
Functionoptional function to apply to each item in a collection; it will be executed prior to applying the value to the new object. Return false to prevent the copy.
-
c
Objectoptional execution context for f.
-
owner
ObjectOwner object passed when clone is iterating an object. Used to set up context for cloned functions.
-
cloned
Objecthash of previously cloned objects to avoid multiple clones.
delegate
-
type
-
fn
-
el
-
filter
-
context
-
args
Sets up event delegation on a container element. The delegated event will use a supplied filter to test if the callback should be executed. This filter can be either a selector string or a function that returns a Node to use as the currentTarget for the event.
The event object for the delegated event is supplied to the callback function. It is modified slightly in order to support all properties that may be needed for event delegation. 'currentTarget' is set to the element that matched the selector string filter or the Node returned from the filter function. 'container' is set to the element that the listener is delegated from (this normally would be the 'currentTarget').
Filter functions will be called with the arguments that would be passed to the callback function, including the event object as the first parameter. The function should return false (or a falsey value) if the success criteria aren't met, and the Node to use as the event's currentTarget and 'this' object if they are.
Parameters:
-
type
Stringthe event type to delegate
-
fn
Functionthe callback function to execute. This function will be provided the event object for the delegated event.
-
el
String | Nodethe element that is the delegation container
-
filter
String | Functiona selector that must match the target of the event or a function that returns a Node or false.
-
context
Objectoptional argument that specifies what 'this' refers to.
-
args
Object multiple0..n additional arguments to pass on to the callback function. These arguments will be added after the event object.
Returns:
the detach handle
destroy
()
Destroys this YUI instance.
detach
-
type
-
fn
-
context
Detach one or more listeners the from the specified event
Parameters:
-
type
String | ObjectEither the handle to the subscriber or the type of event. If the type is not specified, it will attempt to remove the listener from all hosted events.
-
fn
FunctionThe subscribed function to unsubscribe, if not supplied, all subscribers will be removed.
-
context
ObjectThe custom object passed to subscribe. This is optional, but if supplied will be used to disambiguate multiple listeners that are the same (e.g., you subscribe many object using a function that lives on the prototype)
Returns:
the host
detachAll
-
type
Removes all listeners from the specified event. If the event type is not specified, all listeners from all hosted custom events will be removed.
Parameters:
-
type
StringThe type, or name of the event
dispatch
-
o
-
f
-
c
-
proto
-
action
Calls the specified action method on o if it exists. Otherwise, if o is an
array, calls the action method on Y.Array
, or if o is an object, calls the
action method on Y.Object
.
If o is an array-like object, it will be coerced to an array.
This is intended to be used with array/object iteration methods that share
signatures, such as each()
, some()
, etc.
Parameters:
-
o
ObjectArray or object to dispatch to.
-
f
FunctionIteration callback.
-
value
MixedValue being iterated.
-
key
MixedCurrent object key or array index.
-
object
MixedObject or array being iterated.
-
-
c
Objectthis
object to bind the iteration callback to. -
proto
BooleanIf
true
, prototype properties of objects will be iterated. -
action
StringFunction name to be dispatched on o. For example: 'some', 'each', etc.
Returns:
Returns the value returned by the chosen iteration action, which varies.
dump
-
o
-
d
Returns a simple string representation of the object or array. Other types of objects will be returned unprocessed. Arrays are expected to be indexed.
Returns:
the dump result.
each
-
o
-
f
-
c
-
proto
Executes the supplied function for each item in a collection. Supports arrays, objects, and NodeLists
Parameters:
Returns:
the YUI instance.
error
-
msg
-
[e]
-
[src]
Reports an error.
The reporting mechanism is controlled by the throwFail
configuration
attribute. If throwFail
is falsy, the message is logged. If throwFail
is
truthy, a JS exception is thrown.
If an errorFn
is specified in the config it must return true
to indicate
that the exception was handled and keep it from being thrown.
extend
-
r
-
s
-
px
-
sx
Utility to set up the prototype, constructor and superclass properties to support an inheritance strategy that can chain constructors and methods. Static members will not be inherited.
Parameters:
Returns:
the extended object.
fail
-
message
Forces an assertion error to occur. Shortcut for Y.Assert.fail().
Parameters:
-
message
String(Optional) The message to display with the failure.
fire
-
type
-
arguments
Fire a custom event by name. The callback functions will be executed from the context specified when the event was created, and with the following parameters.
The first argument is the event type, and any additional arguments are passed to the listeners as parameters. If the first of these is an object literal, and the event is configured to emit an event facade, that object is mixed into the event facade and the facade is provided in place of the original object.
If the custom event object hasn't been created, then the event hasn't been published and it has no subscribers. For performance sake, we immediate exit in this case. This means the event won't bubble, so if the intention is that a bubble target be notified, the event must be published on this object first.
Parameters:
-
type
String | ObjectThe type of the event, or an object that contains a 'type' property.
-
arguments
Object*an arbitrary set of parameters to pass to the handler. If the first of these is an object literal and the event is configured to emit an event facade, the event facade will replace that parameter after the properties the object literal contains are copied to the event facade.
Returns:
True if the whole lifecycle of the event went through, false if at any point the event propagation was halted.
getEvent
-
type
-
prefixed
Returns the custom event of the provided type has been created, a falsy value otherwise
Parameters:
Returns:
the custom event or null
getLocation
()
Location
Returns the location
object from the window/frame in which this YUI instance
operates, or undefined
when executing in a non-browser environment
(e.g. Node.js).
It is not recommended to hold references to the window.location
object
outside of the scope of a function in which its properties are being accessed or
its methods are being called. This is because of a nasty bug/issue that exists
in both Safari and MobileSafari browsers:
WebKit Bug 34679.
Returns:
The location
object from the window/frame in which this YUI
instance operates.
getTargets
()
Returns an array of bubble targets for this object.
Returns:
EventTarget[]
guid
-
[pre]
Generates an id string that is unique among all YUI instances in this execution context.
Parameters:
-
[pre]
String optionalPrefix.
Returns:
Unique id.
header
-
name
-
value
Method for setting and deleting IO HTTP headers to be sent with every request.
Hosted as a property on the io
function (e.g. Y.io.header
).
instanceOf
-
o
-
type
Safe instanceof
wrapper that works around a memory leak in IE when the
object being tested is window
or document
.
Unless you are testing objects that may be window
or document
, you
should use the native instanceof
operator instead of this method.
io
-
url
-
config
Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties:
- method
- HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.
- data
- This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.
- xdr
- Defines the transport to be used for cross-domain requests.
By setting this property, the transaction will use the specified
transport instead of XMLHttpRequest. The properties of the
transport object are:
- use
- The transport to be used: 'flash' or 'native'
- dataType
- Set the value to 'XML' if that is the expected response content type.
- form
- Form serialization configuration object. Its properties are:
- id
- Node object or id of HTML form
- useDisabled
true
to also serialize disabled form field values (defaults tofalse
)
- on
- Assigns transaction event subscriptions. Available events are:
- start
- Fires when a request is sent to a resource.
- complete
- Fires when the transaction is complete.
- success
- Fires when the HTTP response status is within the 2xx range.
- failure
- Fires when the HTTP response status is outside the 2xx
range, if an exception occurs, if the transation is aborted,
or if the transaction exceeds a configured
timeout
. - end
- Fires at the conclusion of the transaction
lifecycle, after
success
orfailure
.
<p>Callback functions for
start
andend
receive the id of the transaction as a first argument. Forcomplete
,success
, andfailure
, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If thearguments
property was included in the configuration object passed toY.io()
, the configured data will be passed to all callbacks as the last argument.</p> </dd> - sync
- Pass
true
to make a same-domain transaction synchronous. CAVEAT: This will negatively impact the user experience. Have a very good reason if you intend to use this. - context
- The "
this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using
Y.bind()`. - headers
- Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.
- timeout
- Millisecond threshold for the transaction before being automatically aborted.
- arguments
- User-defined data passed to all registered event handlers.
This value is available as the second argument in the "start" and
"end" event handlers. It is the third argument in the "complete",
"success", and "failure" event handlers. Be sure to quote
this property name in the transaction configuration as
"arguments" is a reserved word in JavaScript (e.g.
Y.io({ ..., "arguments": stuff })
).
Parameters:
Returns:
An object containing:
id
- The transaction ID for this request.
abort
- A function to abort the current transaction.
isInProgress
- A helper to determine whether the current transaction is in progress.
io
- A reference to the IO object for this transaction.
later
-
when
-
o
-
fn
-
data
-
periodic
Executes the supplied function in the context of the supplied object 'when' milliseconds later. Executes the function a single time unless periodic is set to true.
Parameters:
-
when
Numberthe number of milliseconds to wait until the fn is executed.
-
o
Objectthe context object.
-
fn
Function | Stringthe function to execute or the name of the method in the 'o' object to execute.
-
data
Object[Array] data that is provided to the function. This accepts either a single item or an array. If an array is provided, the function is executed with one parameter for each array item. If you need to pass a single array parameter, it needs to be wrapped in an array [myarray].
Note: native methods in IE may not have the call and apply methods. In this case, it will work, but you are limited to four arguments.
-
periodic
Booleanif true, executes continuously at supplied interval until canceled.
Returns:
a timer object. Call the cancel() method on this object to stop the timer.
log
-
msg
-
cat
-
src
-
silent
If the 'debug' config is true, a 'yui:log' event will be dispatched, which the Console widget and anything else can consume. If the 'useBrowserConsole' config is true, it will write to the browser console if available. YUI-specific log messages will only be present in the -debug versions of the JS files. The build system is supposed to remove log statements from the raw and minified versions of the files.
Parameters:
Returns:
YUI instance.
merge
-
objects
Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use clone()
.
Parameters:
-
objects
Object multipleOne or more objects to merge.
Returns:
A new merged object.
message
-
msg
-
cat
-
src
-
silent
Write a system message. This message will be preserved in the minified and raw versions of the YUI files, unlike log statements.
Parameters:
Returns:
YUI instance.
mix
-
receiver
-
supplier
-
[overwrite=false]
-
[whitelist]
-
[mode=0]
-
[merge=false]
Mixes supplier's properties into receiver.
Properties on receiver or receiver's prototype will not be overwritten or
shadowed unless the overwrite parameter is true
, and will not be merged
unless the merge parameter is true
.
In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available:
0
: Default. Object to object.1
: Prototype to prototype.2
: Prototype to prototype and object to object.3
: Prototype to object.4
: Object to prototype.
Parameters:
-
receiver
Function | ObjectThe object or function to receive the mixed properties.
-
supplier
Function | ObjectThe object or function supplying the properties to be mixed.
-
[overwrite=false]
Boolean optionalIf
true
, properties that already exist on the receiver will be overwritten with properties from the supplier. -
[whitelist]
String[] optionalAn array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored.
-
[mode=0]
Number optionalMix mode to use. See above for available modes.
-
[merge=false]
Boolean optionalIf
true
, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both overwrite and merge aretrue
, merge takes precedence.
namespace
-
namespace
Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance.
When called statically, a namespace will be created on the YUI global object:
// Create YUI.your.namespace.here
as nested objects, preserving any
// objects that already exist instead of overwriting them.
YUI.namespace('your.namespace.here');
When called as a method on a YUI instance, a namespace will be created on that instance:
// Creates Y.property.package
.
Y.namespace('property.package');
Dots in the input string cause namespace
to create nested objects for each
token. If any part of the requested namespace already exists, the current
object will be left in place and will not be overwritten. This allows
multiple calls to namespace
to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2.
Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long":
Y.namespace('really.long.nested.namespace');
Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function.
Parameters:
-
namespace
String multipleOne or more namespaces to create.
Returns:
Reference to the last namespace object created.
on
-
type
-
fn
-
[context]
-
[arg*]
Y.on()
can do many things:
- Subscribe to custom events
publish
ed andfire
d from Y - Subscribe to custom events
publish
ed withbroadcast
1 or 2 andfire
d from any object in the YUI instance sandbox - Subscribe to DOM events
- Subscribe to the execution of a method on any object, effectively treating that method as an event
For custom event subscriptions, pass the custom event name as the first argument
and callback as the second. The this
object in the callback will be Y
unless
an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a Node
, NodeList
, HTMLElement
,
array, or simply omitted (the default is the window
object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The this
object in DOM event callbacks will be the Node
targeted by the CSS
selector or other identifier.
on()
subscribers for DOM events or custom events publish
ed with a
defaultFn
can prevent the default behavior with e.preventDefault()
from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
Y.Do.before(...)
.
NOTE: The formal parameter list below is for events, not for function
injection. See Y.Do.before
for that signature.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
once
-
type
-
fn
-
[context]
-
[arg*]
Listen for an event one time. Equivalent to on()
, except that
the listener is immediately detached when executed.
See the on()
method for additional subscription
options.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
onceAfter
-
type
-
fn
-
[context]
-
[arg*]
Listen for an event one time. Equivalent to once()
, except, like after()
,
the subscription callback executes after all on()
subscribers and the event's
defaultFn
(if configured) have executed. Like after()
if any on()
phase
subscriber calls e.preventDefault()
, neither the defaultFn
nor the after()
subscribers will execute.
The listener is immediately detached when executed.
See the on()
method for additional subscription
options.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
one
-
node
Returns a single Node instance bound to the node or the
first element matching the given selector. Returns null if no match found.
Note: For chaining purposes you may want to
use Y.all
, which returns a NodeList when no match is found.
Parameters:
-
node
String | HTMLElementa node or Selector
Returns:
a Node instance or null if no match found.
parseType
-
type
-
[pre]
Takes the type parameter passed to 'on' and parses out the various pieces that could be included in the type. If the event type is passed without a prefix, it will be expanded to include the prefix one is supplied or the event target is configured with a default prefix.
Parameters:
Returns:
an array containing:
- the detach category, if supplied,
- the prefixed event type,
- whether or not this is an after listener,
- the supplied event type
publish
-
type
-
opts
Creates a new custom event of the specified type. If a custom event by that name already exists, it will not be re-created. In either case the custom event is returned.
Parameters:
-
type
Stringthe type, or name of the event
-
opts
Objectoptional config params. Valid properties are:
-
[broadcast=false]
Boolean optionalwhether or not the YUI instance and YUI global are notified when the event is fired.
-
[bubbles=true]
Boolean optionalWhether or not this event bubbles. Events can only bubble if
emitFacade
is true. -
[context=this]
Object optionalthe default execution context for the listeners.
-
[defaultFn]
Function optionalthe default function to execute when this event fires if preventDefault was not called.
-
[emitFacade=false]
Boolean optionalwhether or not this event emits a facade.
-
[prefix]
String optionalthe prefix for this targets events, e.g., 'menu' in 'menu:click'.
-
[fireOnce=false]
Boolean optionalif an event is configured to fire once, new subscribers after the fire will be notified immediately.
-
[async=false]
Boolean optionalfireOnce event listeners will fire synchronously if the event has already fired unless
async
istrue
. -
[preventable=true]
Boolean optionalwhether or not
preventDefault()
has an effect. -
[preventedFn]
Function optionala function that is executed when
preventDefault()
is called. -
[queuable=false]
Boolean optionalwhether or not this event can be queued during bubbling.
-
[silent]
Boolean optionalif silent is true, debug messages are not provided for this event.
-
[stoppedFn]
Function optionala function that is executed when stopPropagation is called.
-
[monitored]
Boolean optionalspecifies whether or not this event should send notifications about when the event has been attached, detached, or published.
-
[type]
String optionalthe event type (valid option if not provided as the first parameter to publish).
-
Returns:
the custom event
rbind
-
f
-
c
-
args
Returns a function that will execute the supplied function in the supplied object's context, optionally adding any additional supplied parameters to the end of the arguments the function is executed with.
Parameters:
Returns:
the wrapped function.
require
-
[modules*]
-
callback
Sugar for loading both legacy and ES6-based YUI modules.
Parameters:
-
[modules*]
String optionalList of module names to import or a single module name.
-
callback
FunctionCallback that gets called once all the modules were loaded. Each parameter of the callback is the export value of the corresponding module in the list. If the module is a legacy YUI module, the YUI instance is used instead of the module exports.
Example:
YUI().require(['es6-set'], function (Y, imports) {
var Set = imports.Set,
set = new Set();
});
setLoadHook
-
fn
Set a method to be called when Get.script
is called in Node.js
Get
will open the file, then pass it's content and it's path
to this method before attaching it. Commonly used for code coverage
instrumentation. Calling this multiple times will only
attach the last hook method. This method is only
available in Node.js.
some
-
o
-
f
-
c
-
proto
Executes the supplied function for each item in a collection. The operation stops if the function returns true. Supports arrays, objects, and NodeLists.
Parameters:
Returns:
true if the function ever returns true, false otherwise.
soon
-
callbackFunction
Y.soon accepts a callback function. The callback function will be called once in a future turn of the JavaScript event loop. If the function requires a specific execution context or arguments, wrap it with Y.bind. Y.soon returns an object with a cancel method. If the cancel method is called before the callback function, the callback function won't be called.
Parameters:
-
callbackFunction
Function
Returns:
An object with a cancel method. If the cancel method is called before the callback function, the callback function won't be called.
stamp
-
o
-
readOnly
Returns a unique id associated with the given object and (if readOnly is falsy) stamps the object with that id so it can be identified in the future.
Stamping an object involves adding a _yuid
property to it that contains
the object's id. One exception to this is that in Internet Explorer, DOM
nodes have a uniqueID
property that contains a browser-generated unique
id, which will be used instead of a YUI-generated id when available.
Parameters:
Returns:
Object's unique id, or null
if readOnly was truthy and
the given object was not already stamped.
subscribe
()
deprecated
subscribe to an event
throttle
-
fn
-
ms
Throttles a call to a method based on the time between calls.
Parameters:
Returns:
Returns a wrapped function that calls fn throttled.
unsubscribe
()
deprecated
detach a listener
unsubscribeAll
-
type
Removes all listeners from the specified event. If the event type is not specified, all listeners from all hosted custom events will be removed.
Parameters:
-
type
StringThe type, or name of the event
use
-
modules
-
[callback]
Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen:
All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the
use()
callback will be executed synchronously after the modules are attached.One or more modules have not yet been loaded, or the Get utility is not available, or the
bootstrap
config option isfalse
. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and theuse()
callback will be executed synchronously.One or more modules are missing and the Loader is not available but the Get utility is, and
bootstrap
is notfalse
. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state:One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the
use()
callback will be executed asynchronously.
Parameters:
Example:
// Loads and attaches dd and its dependencies.
YUI().use('dd', function (Y) {
// ...
});
// Loads and attaches dd and node as well as all of their dependencies.
YUI().use(['dd', 'node'], function (Y) {
// ...
});
// Attaches all modules that have already been loaded.
YUI().use('*', function (Y) {
// ...
});
// Attaches a gallery module.
YUI().use('gallery-yql', function (Y) {
// ...
});
// Attaches a YUI 2in3 module.
YUI().use('yui2-datatable', function (Y) {
// ...
});
when
-
promise
-
[callback]
-
[errback]
Abstraction API allowing you to interact with promises or raw values as if they were promises. If a non-promise object is passed in, a new Resolver is created and scheduled to resolve asynchronously with the provided value.
In either case, a promise is returned. If either callback or errback are
provided, the promise returned is the one returned from calling
promise.then(callback, errback)
on the provided or created promise. If neither
are provided, the original promise is returned.
Parameters:
Returns:
Properties
Global
EventTarget
Hosts YUI page level events. This is where events bubble to when the broadcast config is set to 2. This property is only available if the custom event module is loaded.
GlobalConfig
Object
static
Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts.
Example:
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function (Y) {
// debug files used here
});
YUI({
filter: 'min'
}).use('node', function (Y) {
// min files used here
});
meta
Unknown
The component metadata is stored in Y.Env.meta. Part of the loader module.
version
String
The version number of this YUI instance.
This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree.
YUI_config
Object
Page-level config applied to all YUI instances created on the
current page. This is applied after YUI.GlobalConfig
and before
any instance-level configuration.
Example:
// Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function (Y) {
// debug files used here
});
YUI({
filter: 'min'
}).use('node', function (Y) {
// min files used here
});
Events
available
Executes the callback as soon as the specified element is detected in the DOM. This function expects a selector string for the element(s) to detect. If you already have an element reference, you don't need this event.
Event Payload:
-
type
String'available'
-
fn
Functionthe callback function to execute.
-
el
Stringan selector for the element(s) to attach
-
context
Objectoptional argument that specifies what 'this' refers to.
-
args
Object Multiple0..n additional arguments to pass on to the callback function. These arguments will be added after the event object.
contentready
Executes the callback as soon as the specified element is detected in the DOM with a nextSibling property (indicating that the element's children are available). This function expects a selector string for the element(s) to detect. If you already have an element reference, you don't need this event.
Event Payload:
-
type
String'contentready'
-
fn
Functionthe callback function to execute.
-
el
Stringan selector for the element(s) to attach.
-
context
Objectoptional argument that specifies what 'this' refers to.
-
args
Object Multiple0..n additional arguments to pass on to the callback function. These arguments will be added after the event object.
domready
The domready event fires at the moment the browser's DOM is usable. In most cases, this is before images are fully downloaded, allowing you to provide a more responsive user interface.
In YUI 3, domready subscribers will be notified immediately if that moment has already passed when the subscription is created.
One exception is if the yui.js file is dynamically injected into the page. If this is done, you must tell the YUI instance that you did this in order for DOMReady (and window load events) to fire normally. That configuration option is 'injected' -- set it to true if the yui.js script is not included inline.
This method is part of the 'event-ready' module, which is a submodule of 'event'.
flick
Sets up a "flick" event, that is fired whenever the user initiates a flick gesture on the node where the listener is attached. The subscriber can specify a minimum distance or velocity for which the event is to be fired. The subscriber can also specify if there is a particular axis which they are interested in - "x" or "y". If no axis is specified, the axis along which there was most distance covered is used.
It is recommended that you use Y.bind to set up context and additional arguments for your event handler,
however if you want to pass the context and arguments as additional signature arguments to "on",
you need to provide a null value for the configuration object, e.g: node.on("flick", fn, null, context, arg1, arg2, arg3)
Event Payload:
-
type
String"flick"
-
fn
FunctionThe method the event invokes. It receives an event facade with an e.flick object containing the flick related properties: e.flick.time, e.flick.distance, e.flick.velocity and e.flick.axis, e.flick.start.
-
cfg
ObjectOptional. An object which specifies any of the following:
- minDistance (in pixels, defaults to 10)
- The minimum distance between start and end points, which would qualify the gesture as a flick.
- minVelocity (in pixels/ms, defaults to 0)
- The minimum velocity which would qualify the gesture as a flick.
- preventDefault (defaults to false)
- Can be set to true/false to prevent default behavior as soon as the touchstart/touchend or mousedown/mouseup is received so that things like scrolling or text selection can be prevented. This property can also be set to a function, which returns true or false, based on the event facade passed to it.
- axis (no default)
- Can be set to "x" or "y" if you want to constrain the flick velocity and distance to a single axis. If not defined, the axis along which the maximum distance was covered is used.
gesturemove
Sets up a "gesturemove" event, that is fired on touch devices in response to a single finger "touchmove", and on mouse based devices in response to a "mousemove".
By default this event is only fired when the same node has received a "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, if they want to listen for this event without an initial "gesturemovestart".
By default this event sets up it's internal "touchmove" and "mousemove" DOM listeners on the document element. The subscriber can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.
This event can also be listened for using node.delegate().
It is recommended that you use Y.bind to set up context and additional arguments for your event handler,
however if you want to pass the context and arguments as additional signature arguments to on/delegate,
you need to provide a null value for the configuration object, e.g: node.on("gesturemove", fn, null, context, arg1, arg2, arg3)
Event Payload:
-
type
String"gesturemove"
-
fn
FunctionThe method the event invokes. It receives the event facade of the underlying DOM event (mousemove or touchmove.touches[0]) which contains position co-ordinates.
-
cfg
ObjectOptional. An object which specifies:
- standAlone (defaults to false)
- true, if the subscriber should be notified even if a "gesturemovestart" has not occured on the same node.
- root (defaults to document)
- The node to which the internal DOM listeners should be attached.
- preventDefault (defaults to false)
- Can be set to true/false to prevent default behavior as soon as the touchmove or mousemove is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
gesturemoveend
Sets up a "gesturemoveend" event, that is fired on touch devices in response to a single finger "touchend", and on mouse based devices in response to a "mouseup".
By default this event is only fired when the same node has received a "gesturemove" or "gesturemovestart" event. The subscriber can set standAlone to true, in the configuration properties, if they want to listen for this event without a preceding "gesturemovestart" or "gesturemove".
By default this event sets up it's internal "touchend" and "mouseup" DOM listeners on the document element. The subscriber can set the root configuration property, to specify which node to attach DOM listeners to, if different from the document.
This event can also be listened for using node.delegate().
It is recommended that you use Y.bind to set up context and additional arguments for your event handler,
however if you want to pass the context and arguments as additional signature arguments to on/delegate,
you need to provide a null value for the configuration object, e.g: node.on("gesturemoveend", fn, null, context, arg1, arg2, arg3)
Event Payload:
-
type
String"gesturemoveend"
-
fn
FunctionThe method the event invokes. It receives the event facade of the underlying DOM event (mouseup or touchend.changedTouches[0]).
-
cfg
ObjectOptional. An object which specifies:
- standAlone (defaults to false)
- true, if the subscriber should be notified even if a "gesturemovestart" or "gesturemove" has not occured on the same node.
- root (defaults to document)
- The node to which the internal DOM listeners should be attached.
- preventDefault (defaults to false)
- Can be set to true/false to prevent default behavior as soon as the touchend or mouseup is received. As with gesturemovestart, can also be set to function which returns true/false based on the event facade passed to it.
gesturemovestart
Sets up a "gesturemovestart" event, that is fired on touch devices in response to a single finger "touchstart", and on mouse based devices in response to a "mousedown". The subscriber can specify the minimum time and distance thresholds which should be crossed before the "gesturemovestart" is fired and for the mouse, which button should initiate a "gesturemovestart". This event can also be listened for using node.delegate().
It is recommended that you use Y.bind to set up context and additional arguments for your event handler,
however if you want to pass the context and arguments as additional signature arguments to on/delegate,
you need to provide a null value for the configuration object, e.g: node.on("gesturemovestart", fn, null, context, arg1, arg2, arg3)
Event Payload:
-
type
String"gesturemovestart"
-
fn
FunctionThe method the event invokes. It receives the event facade of the underlying DOM event (mousedown or touchstart.touches[0]) which contains position co-ordinates.
-
cfg
ObjectOptional. An object which specifies:
- minDistance (defaults to 0)
- The minimum distance threshold which should be crossed before the gesturemovestart is fired
- minTime (defaults to 0)
- The minimum time threshold for which the finger/mouse should be help down before the gesturemovestart is fired
- button (no default)
- In the case of a mouse input device, if the event should only be fired for a specific mouse button.
- preventDefault (defaults to false)
- Can be set to true/false to prevent default behavior as soon as the touchstart or mousedown is received (that is before minTime or minDistance thresholds are crossed, and so before the gesturemovestart listener is notified) so that things like text selection and context popups (on touch devices) can be prevented. This property can also be set to a function, which returns true or false, based on the event facade passed to it (for example, DragDrop can determine if the target is a valid handle or not before preventing default).
hashchange
Synthetic window.onhashchange
event that normalizes differences
across browsers and provides support for browsers that don't natively support
onhashchange
.
This event is provided by the history-hash
module.
Event Payload:
-
e
EventFacadeEvent facade with the following additional properties:
- oldHash
- Previous hash fragment value before the change.
- oldUrl
- Previous URL (including the hash fragment) before the change.
- newHash
- New hash fragment value after the change.
- newUrl
- New URL (including the hash fragment) after the change.
Example:
YUI().use('history-hash', function (Y) {
Y.on('hashchange', function (e) {
// Handle hashchange events on the current window.
}, Y.config.win);
});
key
Add a key listener. The listener will only be notified if the keystroke detected meets the supplied specification. The specification is a string that is defined as:
- spec
[{type}:]{code}[,{code}]
- type
"down", "up", or "press"
- code
{keyCode|character|keyName}[+{modifier}]
- modifier
"shift", "ctrl", "alt", or "meta"
- keyName
"enter", "space", "backspace", "esc", "tab", "pageup", or "pagedown"
Examples:
Y.on("key", callback, "press:12,65+shift+ctrl", "#my-input");
Y.delegate("key", preventSubmit, "#forms", "enter", "input[type=text]");
Y.one("doc").on("key", viNav, "j,k,l,;");
mousewheel
Mousewheel event. This listener is automatically attached to the correct target, so one should not be supplied. Mouse wheel direction and velocity is stored in the 'wheelDelta' field.
valuechange
Synthetic event that fires when the value
property of an <input>
,
<textarea>
, <select>
, or [contenteditable="true"]
node changes as a
result of a user-initiated keystroke, mouse operation, or input method
editor (IME) input event.
Unlike the onchange
event, this event fires when the value actually changes
and not when the element loses focus. This event also reports IME and
multi-stroke input more reliably than oninput
or the various key events across
browsers.
For performance reasons, only focused nodes are monitored for changes, so programmatic value changes on nodes that don't have focus won't be detected.
Event Payload:
Example:
YUI().use('event-valuechange', function (Y) {
Y.one('#my-input').on('valuechange', function (e) {
Y.log('previous value: ' + e.prevVal);
Y.log('new value: ' + e.newVal);
});
});
windowresize
Old firefox fires the window resize event once when the resize action finishes, other browsers fire the event periodically during the resize. This code uses timeout logic to simulate the Firefox behavior in other browsers.