API Docs for: 1.0 pre
Show:

Ember.Set Class

An unordered collection of objects.

A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order.

All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays.

Creating a Set

You can create a set like you would most objects using new Ember.Set(). Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor.

Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling Ember.Set#copy().

// creates a new empty set
var foundNames = new Ember.Set();

// creates a set with four names in it.
var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P

// creates a copy of the names set.
var namesCopy = new Ember.Set(names);

// same as above.
var anotherNamesCopy = names.copy();

Adding/Removing Objects

You generally add or remove objects from a set using add() or remove(). You can add any type of object including primitives such as numbers, strings, and booleans.

Unlike arrays, objects can only exist one time in a set. If you call add() on a set with the same object multiple times, the object will only be added once. Likewise, calling remove() with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again.

NOTE: You cannot add/remove null or undefined to a set. Any attempt to do so will be ignored.

In addition to add/remove you can also call push()/pop(). Push behaves just like add() but pop(), unlike remove() will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in.

Testing for an Object

To test for an object's presence in a set you simply call Ember.Set#contains().

Observing changes

When using Ember.Set, you can observe the "[]" property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See Ember.Enumerable for more information on enumerables.

This is often unhelpful. If you are filtering sets of objects, for instance, it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well.

Other Methods

Ember.Set primary implements other mixin APIs. For a complete reference on the methods you will use with Ember.Set, please consult these mixins. The most useful ones will be Ember.Enumerable and Ember.MutableEnumerable which implement most of the common iterator methods you are used to on Array.

Note that you can also use the Ember.Copyable and Ember.Freezable APIs on Ember.Set as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call frozenCopy() on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified.

Methods

_scheduledDestroy

() private

Invoked by the run loop to actually destroy the object. This is scheduled for execution by the destroy method.

add

(
  • obj
)
Ember.Set

Adds an object to the set. Only non-null objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect.

This is an alias for Ember.MutableEnumerable.addObject().

var colors = new Ember.Set();
colors.add("blue");     // ["blue"]
colors.add("blue");     // ["blue"]
colors.add("red");      // ["blue", "red"]
colors.add(null);       // ["blue", "red"]
colors.add(undefined);  // ["blue", "red"]

Parameters:

  • obj Object

    The object to add.

Returns:

Ember.Set:

The set itself.

addEach

(
  • objects
)
Ember.Set

Adds each object in the passed enumerable to the set.

This is an alias of Ember.MutableEnumerable.addObjects()

var colors = new Ember.Set();
colors.addEach(["red", "green", "blue"]);  // ["red", "green", "blue"]

Parameters:

Returns:

Ember.Set:

The set itself.

addObject

(
  • object
)
Object

Required. You must implement this method to apply this mixin.

Attempts to add the passed object to the receiver if the object is not already present in the collection. If the object is present, this method has no effect.

If the passed object is of a type not supported by the receiver, then this method should raise an exception.

Parameters:

  • object Object

    The object to add to the enumerable.

Returns:

Object:

the passed object

addObjects

(
  • objects
)
Object

Adds each object in the passed enumerable to the receiver.

Parameters:

Returns:

Object:

receiver

clear

() Ember.Set

Clears the set. This is useful if you want to reuse an existing set without having to recreate it.

var colors = new Ember.Set(["red", "green", "blue"]);
colors.length;  // 3
colors.clear();
colors.length;  // 0

Returns:

Ember.Set:

An empty Set

copy

(
  • deep
)
Object

Override to return a copy of the receiver. Default implementation raises an exception.

Parameters:

  • deep Boolean

    if true, a deep copy of the object should be made

Returns:

Object:

copy of receiver

destroy

() Ember.Object

Destroys an object by setting the isDestroyed flag and removing its metadata, which effectively destroys observers and bindings.

If you try to set a property on a destroyed object, an exception will be raised.

Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately.

Returns:

Ember.Object:

receiver

eachComputedProperty

(
  • callback
  • binding
)

Iterate over each computed property for the class, passing its name and any associated metadata (see metaForProperty) to the callback.

Parameters:

freeze

() Object

Freezes the object. Once this method has been called the object should no longer allow any properties to be edited.

Returns:

Object:

receiver

frozenCopy

() Object

If the object implements Ember.Freezable, then this will return a new copy if the object is not frozen and the receiver if the object is frozen.

Raises an exception if you try to call this method on a object that does not support freezing.

You should use this method whenever you want a copy of a freezable object since a freezable object can simply return itself without actually consuming more memory.

Returns:

Object:

copy of receiver or receiver

init

()

An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition.

Example:

App.Person = Ember.Object.extend({
  init: function() {
    alert('Name is ' + this.get('name'));
  }
});

var steve = App.Person.create({
  name: "Steve"
});

// alerts 'Name is Steve'.

NOTE: If you do override init for a framework class like Ember.View or Ember.ArrayController, be sure to call this._super() in your init declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.

isEqual

(
  • obj
)
Boolean

Returns true if the passed object is also an enumerable that contains the same objects as the receiver.

var colors = ["red", "green", "blue"],
    same_colors = new Ember.Set(colors);

same_colors.isEqual(colors);               // true
same_colors.isEqual(["purple", "brown"]);  // false

Parameters:

Returns:

Boolean:

metaForProperty

(
  • key
)

In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection.

You can pass a hash of these values to a computed property like this:

person: function() {
  var personId = this.get('personId');
  return App.Person.create({ id: personId });
}.property().meta({ type: App.Person })

Once you've done this, you can retrieve the values saved to the computed property from your class like this:

MyClass.metaForProperty('person');

This will return the original hash that was passed to meta().

Parameters:

pop

() Object

Removes the last element from the set and returns it, or null if it's empty.

var colors = new Ember.Set(["green", "blue"]);
colors.pop();  // "blue"
colors.pop();  // "green"
colors.pop();  // null

Returns:

Object:

The removed object from the set or null.

push

() Ember.Set

Inserts the given object on to the end of the set. It returns the set itself.

This is an alias for Ember.MutableEnumerable.addObject().

var colors = new Ember.Set();
colors.push("red");   // ["red"]
colors.push("green"); // ["red", "green"]
colors.push("blue");  // ["red", "green", "blue"]

Returns:

Ember.Set:

The set itself.

remove

(
  • obj
)
Ember.Set

Removes the object from the set if it is found. If you pass a null value or an object that is already not in the set, this method will have no effect. This is an alias for Ember.MutableEnumerable.removeObject().

var colors = new Ember.Set(["red", "green", "blue"]);
colors.remove("red");     // ["blue", "green"]
colors.remove("purple");  // ["blue", "green"]
colors.remove(null);      // ["blue", "green"]

Parameters:

  • obj Object

    The object to remove

Returns:

Ember.Set:

The set itself.

removeEach

(
  • objects
)
Ember.Set

Removes each object in the passed enumerable to the set.

This is an alias of Ember.MutableEnumerable.removeObjects()

var colors = new Ember.Set(["red", "green", "blue"]);
colors.removeEach(["red", "blue"]);  //  ["green"]

Parameters:

Returns:

Ember.Set:

The set itself.

removeObject

(
  • object
)
Object

Required. You must implement this method to apply this mixin.

Attempts to remove the passed object from the receiver collection if the object is present in the collection. If the object is not present, this method has no effect.

If the passed object is of a type not supported by the receiver, then this method should raise an exception.

Parameters:

  • object Object

    The object to remove from the enumerable.

Returns:

Object:

the passed object

removeObjects

(
  • objects
)
Object

Removes each object in the passed enumerable from the receiver.

Parameters:

Returns:

Object:

receiver

reopen

()

Augments a constructor's prototype with additional properties and functions:

MyObject = Ember.Object.extend({
  name: 'an object'
});

o = MyObject.create();
o.get('name'); // 'an object'

MyObject.reopen({
  say: function(msg){
    console.log(msg);
  }
})

o2 = MyObject.create();
o2.say("hello"); // logs "hello"

o.say("goodbye"); // logs "goodbye"

To add functions and properties to the constructor itself, see reopenClass

reopenClass

()

Augments a constructor's own properties and functions:

MyObject = Ember.Object.extend({
  name: 'an object'
});

MyObject.reopenClass({
  canBuild: false
});

MyObject.canBuild; // false
o = MyObject.create();

In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class.

App.Person = Ember.Object.extend({
  name : "",
  sayHello : function(){
    alert("Hello. My name is " + this.get('name'));
  }
});

App.Person.reopenClass({
  species : "Homo sapiens",
  createPerson: function(newPersonsName){
    return App.Person.create({
      name:newPersonsName
    });
  }
});

var tom = App.Person.create({
  name : "Tom Dale"
});
var yehuda = App.Person.createPerson("Yehuda Katz");

tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(App.Person.species); // "Homo sapiens"

Note that species and createPerson are not valid on the tom and yehuda variables. They are only valid on App.Person.

To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen

shift

() Object

Removes the last element from the set and returns it, or null if it's empty.

This is an alias for Ember.Set.pop().

var colors = new Ember.Set(["green", "blue"]);
colors.shift();  // "blue"
colors.shift();  // "green"
colors.shift();  // null

Returns:

Object:

The removed object from the set or null.

toString

() String

Returns a string representation which attempts to provide more information than Javascript's toString typically does, in a generic way for all Ember objects.

App.Person = Em.Object.extend()
person = App.Person.create()
person.toString() //=> "<App.Person:ember1024>"

If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass:

Student = App.Person.extend()
student = Student.create()
student.toString() //=> "<(subclass of App.Person):ember1025>"

If the method toStringExtension is defined, its return value will be included in the output.

App.Teacher = App.Person.extend({
  toStringExtension: function() {
    return this.get('fullName');
  }
});
teacher = App.Teacher.create()
teacher.toString(); //=> "<App.Teacher:ember1026:Tom Dale>"

Returns:

String:

string representation

unshift

() Ember.Set

Inserts the given object on to the end of the set. It returns the set itself.

This is an alias of Ember.Set.push()

var colors = new Ember.Set();
colors.unshift("red");    // ["red"]
colors.unshift("green");  // ["red", "green"]
colors.unshift("blue");   // ["red", "green", "blue"]

Returns:

Ember.Set:

The set itself.

willDestroy

()

Override to implement teardown.

Properties

concatenatedProperties

Array

Defines the properties that will be concatenated from the superclass (instead of overridden).

By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the classNames property of Ember.View.

Here is some sample code showing the difference between a concatenated property and a normal one:

App.BarView = Ember.View.extend({
  someNonConcatenatedProperty: ['bar'],
  classNames: ['bar']
});

App.FooBarView = App.BarView.extend({
  someNonConcatenatedProperty: ['foo'],
  classNames: ['foo'],
});

var fooBarView = App.FooBarView.create();
fooBarView.get('someNonConcatenatedProperty'); // ['foo']
fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo']

This behavior extends to object creation as well. Continuing the above example:

var view = App.FooBarView.create({
  someNonConcatenatedProperty: ['baz'],
  classNames: ['baz']
})
view.get('someNonConcatenatedProperty'); // ['baz']
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']

Adding a single property that is not an array will just add it in the array:

var view = App.FooBarView.create({
  classNames: 'baz'
})
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']

Using the concatenatedProperties property, we can tell to Ember that mix the content of the properties.

In Ember.View the classNameBindings and attributeBindings properties are also concatenated, in addition to classNames.

This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass).

Default: null

isDestroyed

Unknown

Destroyed object property flag.

if this property is true the observers and bindings were already removed by the effect of calling the destroy() method.

Default: false

isDestroying

Unknown

Destruction scheduled flag. The destroy() method has been called.

The object stays intact until the end of the run loop at which point the isDestroyed flag is set.

Default: false

isFrozen

Boolean

Set to true when the object is frozen. Use this property to detect whether your object is frozen or not.

length

Number

This property will change as the number of objects in the set changes.

Default: 0