W3cubDocs

/Ember.js

Ember (public)

Defined in: packages/ember-metal/lib/core.js:8
Module: ember

$ public

Alias for jQuery

A Ember.NativeArray public

returns
Ember.NativeArray

Creates an Ember.NativeArray from an Array like object. Does not modify the original object's contents. Ember.A is not needed if EmberENV.EXTEND_PROTOTYPES is true (the default value). However, it is recommended that you use Ember.A when creating addons for ember or when you can not guarantee that EmberENV.EXTEND_PROTOTYPES will be true.

Example

export default Ember.Component.extend({
  tagName: 'ul',
  classNames: ['pagination'],

  init() {
    this._super(...arguments);

    if (!this.get('content')) {
      this.set('content', Ember.A());
    }
  }
});

K Object public

returns
Object

An empty function useful for some operations. Always returns this.

addListener (obj, eventName, target, method, once) public

obj
eventName
String
target
Object|Function
A target object or a function
method
Function|String
A function or the name of a function to be called on `target`
once
Boolean
A flag whether a function should only be called once

Add an event listener

addObserver (obj, _path, target, method) public

obj
_path
String
target
Object|Function
method
Function|String

aliasMethod (methodName) public

methodName
String
name of the method to alias

Makes a method available via an additional name.

App.Person = Ember.Object.extend({
  name: function() {
    return 'Tomhuda Katzdale';
  },
  moniker: Ember.aliasMethod('name')
});

let goodGuy = App.Person.create();

goodGuy.name();    // 'Tomhuda Katzdale'
goodGuy.moniker(); // 'Tomhuda Katzdale'

assert (desc, test) public

desc
String
A description of the assertion. This will become the text of the Error thrown if the assertion fails.
test
Boolean
Must be truthy for the assertion to pass. If falsy, an exception will be thrown.

Define an assertion that will throw an exception if the condition is not met.

  • In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.
// Test for truthiness
Ember.assert('Must pass a valid object', obj);

// Fail unconditionally
Ember.assert('This code path should never be run');

assign (original, args) Object public

original
Object
The object to assign into
args
Object
The objects to copy properties from
returns
Object

Copy properties from a source object to a target object.

var a = { first: 'Yehuda' };
var b = { last: 'Katz' };
var c = { company: 'Tilde Inc.' };
Ember.assign(a, b, c); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' }, b === { last: 'Katz' }, c === { company: 'Tilde Inc.' }

bind (obj, to, from) Ember.Binding public

obj
Object
The root object of the transform.
to
String
The path to the 'to' side of the binding. Must be relative to obj.
from
String
The path to the 'from' side of the binding. Must be relative to obj or a global path.
returns
Ember.Binding
binding instance

Global helper method to create a new binding. Just pass the root object along with a to and from path to create and connect the binding.

cacheFor (obj, key) Object public

obj
Object
the object whose property you want to check
key
String
the name of the property whose cached value you want to return
returns
Object
the cached value

Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created.

compare (v, w) Number public

v
Object
First value to compare
w
Object
Second value to compare
returns
Number
-1 if v < w, 0 if v = w and 1 if v > w.

Compares two javascript values and returns:

  • -1 if the first is smaller than the second,
  • 0 if both are equal,
  • 1 if the first is greater than the second.

    Ember.compare('hello', 'hello');  // 0
    Ember.compare('abc', 'dfg');      // -1
    Ember.compare(2, 1);              // 1

If the types of the two objects are different precedence occurs in the following order, with types earlier in the list considered < types later in the list:

  • undefined
  • null
  • boolean
  • number
  • string
  • array
  • object
  • instance
  • function
  • class
  • date

    Ember.compare('hello', 50);       // 1
    Ember.compare(50, 'hello');       // -1

copy (obj, deep) Object public

obj
Object
The object to clone
deep
Boolean
If true, a deep copy of the object is made.
returns
Object
The copied object

Creates a shallow copy of the passed object. A deep copy of the object is returned if the optional deep argument is true.

If the passed object implements the Ember.Copyable interface, then this function will delegate to the object's copy() method and return the result. See Ember.Copyable for further details.

For primitive values (which are immutable in JavaScript), the passed object is simply returned.

debug (message) public

message
String
A debug message to display.

Display a debug notice.

  • In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.
Ember.debug('I\'m a debug notice!');

deprecate (message, test, options) public

message
String
A description of the deprecation.
test
Boolean
A boolean. If falsy, the deprecation will be displayed.
options
Object

Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only).

  • In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.

get (obj, keyName) Object public

obj
Object
The object to retrieve from.
keyName
String
The property key to retrieve
returns
Object
the property value or `null`.

Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the unknownProperty method then that will be invoked.

Ember.get(obj, "name");

If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.)

On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the unknownProperty handler. Otherwise you can ignore this method.

Note that if the object itself is undefined, this method will throw an error.

getEngineParent (engine) EngineInstance public

engine
EngineInstance
An engine instance.
returns
EngineInstance
The parent engine instance.

getEngineParent retrieves an engine instance's parent instance.

getOwner (object) Object public

object
Object
An object with an owner.
returns
Object
An owner object.

Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handled its instantiation and manages its lifetime.

getOwner fetches the owner object responsible for an instance. This can be used to lookup or resolve other class instances, or register new factories into the owner.

For example, this component dynamically looks up a service based on the audioType passed as an attribute:

import Ember from 'ember';

// Usage:
//
//   {{play-audio audioType=model.audioType audioFile=model.file}}
//
export default Ember.Component.extend({
  audioService: Ember.computed('audioType', function() {
    let owner = Ember.getOwner(this);
    return owner.lookup(`service:${this.get('audioType')}`);
  }),
  click() {
    let player = this.get('audioService');
    player.play(this.get('audioFile'));
  }
});

getProperties (obj, list) Object public

obj
Object
list
String...|Array
of keys to get
returns
Object

To get multiple properties at once, call Ember.getProperties with an object followed by a list of strings or an array:

Ember.getProperties(record, 'firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }

is equivalent to:

Ember.getProperties(record, ['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }

getWithDefault (obj, keyName, defaultValue) Object public

obj
Object
The object to retrieve from.
keyName
String
The name of the property to retrieve
defaultValue
Object
The value to return if the property value is undefined
returns
Object
The property value or the defaultValue.

Retrieves the value of a property from an Object, or a default value in the case that the property returns undefined.

Ember.getWithDefault(person, 'lastName', 'Doe');

guidFor (obj) String public

obj
Object
any object, string, number, Element, or primitive
returns
String
the unique guid for this instance.

Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, Ember.Object-based or not, but be aware that it will add a _guid property.

You can also use this method on DOM Element objects.

isArray (obj) Boolean public

obj
Object
The object to test
returns
Boolean
true if the passed object is an array or Array-like

Returns true if the passed object is an array or Array-like.

Objects are considered Array-like if any of the following are true:

  • the object is a native Array
  • the object has an objectAt property
  • the object is an Object, and has a length property

Unlike Ember.typeOf this method returns true even if the passed object is not formally an array but appears to be array-like (i.e. implements Ember.Array)

Ember.isArray();                                          // false
Ember.isArray([]);                                        // true
Ember.isArray(Ember.ArrayProxy.create({ content: [] }));  // true

isBlank (obj) Boolean public

obj
Object
Value to test
returns
Boolean

A value is blank if it is empty or a whitespace string.

Ember.isBlank();                // true
Ember.isBlank(null);            // true
Ember.isBlank(undefined);       // true
Ember.isBlank('');              // true
Ember.isBlank([]);              // true
Ember.isBlank('\n\t');          // true
Ember.isBlank('  ');            // true
Ember.isBlank({});              // false
Ember.isBlank('\n\t Hello');    // false
Ember.isBlank('Hello world');   // false
Ember.isBlank([1,2,3]);         // false

isEmpty (obj) Boolean public

obj
Object
Value to test
returns
Boolean

Verifies that a value is null or an empty string, empty array, or empty function.

Constrains the rules on Ember.isNone by returning true for empty string and empty arrays.

Ember.isEmpty();                // true
Ember.isEmpty(null);            // true
Ember.isEmpty(undefined);       // true
Ember.isEmpty('');              // true
Ember.isEmpty([]);              // true
Ember.isEmpty({});              // false
Ember.isEmpty('Adam Hawkins');  // false
Ember.isEmpty([0,1,2]);         // false
Ember.isEmpty('\n\t');          // false
Ember.isEmpty('  ');            // false

isEqual (a, b) Boolean public

a
Object
first object to compare
b
Object
second object to compare
returns
Boolean

Compares two objects, returning true if they are equal.

Ember.isEqual('hello', 'hello');                   // true
Ember.isEqual(1, 2);                               // false

isEqual is a more specific comparison than a triple equal comparison. It will call the isEqual instance method on the objects being compared, allowing finer control over when objects should be considered equal to each other.

let Person = Ember.Object.extend({
  isEqual(other) { return this.ssn == other.ssn; }
});

let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'});
let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'});

Ember.isEqual(personA, personB); // true

Due to the expense of array comparisons, collections will never be equal to each other even if each of their items are equal to each other.

Ember.isEqual([4, 2], [4, 2]);                     // false

isNone (obj) Boolean public

obj
Object
Value to test
returns
Boolean

Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing.

Ember.isNone();              // true
Ember.isNone(null);          // true
Ember.isNone(undefined);     // true
Ember.isNone('');            // false
Ember.isNone([]);            // false
Ember.isNone(function() {}); // false

isPresent (obj) Boolean public

obj
Object
Value to test
returns
Boolean

A value is present if it not isBlank.

Ember.isPresent();                // false
Ember.isPresent(null);            // false
Ember.isPresent(undefined);       // false
Ember.isPresent('');              // false
Ember.isPresent('  ');            // false
Ember.isPresent('\n\t');          // false
Ember.isPresent([]);              // false
Ember.isPresent({ length: 0 })    // false
Ember.isPresent(false);           // true
Ember.isPresent(true);            // true
Ember.isPresent('string');        // true
Ember.isPresent(0);               // true
Ember.isPresent(function() {})    // true
Ember.isPresent({});              // true
Ember.isPresent(false);           // true
Ember.isPresent('\n\t Hello');    // true
Ember.isPresent([1,2,3]);         // true

merge (original, updates) Object public

original
Object
The object to merge into
updates
Object
The object to copy properties from
returns
Object

Merge the contents of two objects together into the first object.

Ember.merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' }
var a = { first: 'Yehuda' };
var b = { last: 'Katz' };
Ember.merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }

observer (propertyNames, func) public

propertyNames
String
func
Function
returns
func

Specify a method that observes property changes.

Ember.Object.extend({
  valueObserver: Ember.observer('value', function() {
    // Executes whenever the "value" property changes
  })
});

Also available as Function.prototype.observes if prototype extensions are enabled.

on (eventNames, func) public

eventNames
String
func
Function
returns
func

Define a property as a function that should be executed when a specified event or events are triggered.

let Job = Ember.Object.extend({
  logCompleted: Ember.on('completed', function() {
    console.log('Job completed!');
  })
});

let job = Job.create();

Ember.sendEvent(job, 'completed'); // Logs 'Job completed!'

removeListener (obj, eventName, target, method) public

obj
eventName
String
target
Object|Function
A target object or a function
method
Function|String
A function or the name of a function to be called on `target`

Remove an event listener

Arguments should match those passed to Ember.addListener.

removeObserver (obj, path, target, method) public

obj
path
String
target
Object|Function
method
Function|String

runInDebug (func) public

func
Function
The function to be executed.

Run a function meant for debugging.

  • In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.
Ember.runInDebug(() => {
  Ember.Component.reopen({
    didInsertElement() {
      console.log("I'm happy");
    }
  });
});

sendEvent (obj, eventName, params, actions, meta) public

obj
eventName
String
params
Array
Optional parameters for each listener.
actions
Array
Optional array of actions (listeners).
meta
Meta
Optional meta to lookup listeners
returns
true

Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked.

set (obj, keyName, value) Object public

obj
Object
The object to modify.
keyName
String
The property key to set
value
Object
The value to set
returns
Object
the passed value.

Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the setUnknownProperty method then that will be invoked as well.

Ember.set(obj, "name", value);

setOwner (object, object) public

object
Object
An object instance.
object
Object
The new owner object of the object instance.

setOwner forces a new owner on a given object instance. This is primarily useful in some testing cases.

setProperties (obj, properties) public

obj
properties
Object
returns
properties

Set a list of properties on an object. These properties are set inside a single beginPropertyChanges and endPropertyChanges batch, so observers will be buffered.

let anObject = Ember.Object.create();

anObject.setProperties({
  firstName: 'Stanley',
  lastName: 'Stuart',
  age: 21
});

tryInvoke (obj, methodName, args) * public

obj
Object
The object to check for the method
methodName
String
The method name to check for
args
Array
The arguments to pass to the method
returns
*
the return value of the invoked method or undefined if it cannot be invoked

Checks to see if the methodName exists on the obj, and if it does, invokes it with the arguments passed.

let d = new Date('03/15/2013');

Ember.tryInvoke(d, 'getTime');              // 1363320000000
Ember.tryInvoke(d, 'setFullYear', [2014]);  // 1394856000000
Ember.tryInvoke(d, 'noSuchMethod', [2014]); // undefined

trySet (root, path, value) public

root
Object
The object to modify.
path
String
The property path to set
value
Object
The value to set

Error-tolerant form of Ember.set. Will not blow up if any part of the chain is undefined, null, or destroyed.

This is primarily used when syncing bindings, which may try to update after an object has been destroyed.

typeOf (item) String public

item
Object
the item to check
returns
String
the type

Returns a consistent type for the passed object.

Use this instead of the built-in typeof to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned:

| Return Value  | Meaning                                              |
|---------------|------------------------------------------------------|
| 'string'      | String primitive or String object.                   |
| 'number'      | Number primitive or Number object.                   |
| 'boolean'     | Boolean primitive or Boolean object.                 |
| 'null'        | Null value                                           |
| 'undefined'   | Undefined value                                      |
| 'function'    | A function                                           |
| 'array'       | An instance of Array                                 |
| 'regexp'      | An instance of RegExp                                |
| 'date'        | An instance of Date                                  |
| 'filelist'    | An instance of FileList                              |
| 'class'       | An Ember class (created using Ember.Object.extend()) |
| 'instance'    | An Ember object instance                             |
| 'error'       | An instance of the Error object                      |
| 'object'      | A JavaScript object not inheriting from Ember.Object |

Examples:

Ember.typeOf();                       // 'undefined'
Ember.typeOf(null);                   // 'null'
Ember.typeOf(undefined);              // 'undefined'
Ember.typeOf('michael');              // 'string'
Ember.typeOf(new String('michael'));  // 'string'
Ember.typeOf(101);                    // 'number'
Ember.typeOf(new Number(101));        // 'number'
Ember.typeOf(true);                   // 'boolean'
Ember.typeOf(new Boolean(true));      // 'boolean'
Ember.typeOf(Ember.A);                // 'function'
Ember.typeOf([1, 2, 90]);             // 'array'
Ember.typeOf(/abc/);                  // 'regexp'
Ember.typeOf(new Date());             // 'date'
Ember.typeOf(event.target.files);     // 'filelist'
Ember.typeOf(Ember.Object.extend());  // 'class'
Ember.typeOf(Ember.Object.create());  // 'instance'
Ember.typeOf(new Error('teamocil'));  // 'error'

// 'normal' JavaScript object
Ember.typeOf({ a: 'b' });             // 'object'

warn (message, test, options) public

message
String
A warning to display.
test
Boolean
An optional boolean. If falsy, the warning will be displayed.
options
Object
An object that can be used to pass a unique `id` for this warning. The `id` can be used by Ember debugging tools to change the behavior (raise, log, or silence) for that specific warning. The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"

Display a warning with the provided message.

  • In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.

© 2017 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://emberjs.com/api/ember/2.14/classes/Ember/methods