Class: SetModel

maria. SetModel

new SetModel()

A constructor function to create new set model objects. A set model object is a collection of elements. An element can only be included once in a set model object.

The constructor takes multiple arguments and populates the set model with those elements.

var alpha = new maria.Model();
alpha.name = 'Alpha';
var beta = new maria.Model();
beta.name = 'Beta';

var setModel = new maria.SetModel(alpha, beta);

You can create an empty set model object.

var setModel = new maria.SetModel(); 

What makes a set model object interesting in comparison to a set is that a set model object is a model object that dispatches "change" events when elements are added or deleted from the the set.

var view = {
    update: function(evt) {
        alert(setModel.size + ' element(s) in the set.');
    }
};
maria.on(setModel, 'change', view, 'update');

You can add elements to the set. Adding an element that is already in the set has no effect. The add method returns true if the element is added to the set.

setModel.add(alpha); // returns true, alpha was added
setModel.add(alpha); // returns false, alpha not added again

The add method accepts multiple objects and only dispatches a single "change" event if any of the arguments are added to the set model object.

setModel.add(alpha, beta); // returns true, beta was added

When elements are added to the set model object, all "change" event listeners are passed an event object with an addedTargets property which has an array containing all elements added to the set model object.

You can check if an element is in the set.

setModel.has(alpha); // returns true, alpha was added above

You can get the number of elements in the set.

setModel.size; // returns 2

An element can be deleted from the set. Removing it multiple times has no effect. The delete method returns true if the element is deleted from the set.

setModel['delete'](alpha); // returns true, alpha was deleted
setModel['delete'](alpha); // returns false, alpha wasn't in set

The delete method accepts multiple objects.

setModel['delete'](alpha, beta); // returns true, beta was removed

When elements are deleted from the set model object, all "change" event listeners are passed an event object with a deletedTargets property which is an array containing all elements deleted from the set model object.

Note that delete is a keyword in JavaScript and to keep old browsers happy you need to write setModel['delete']. You can write setModel.delete if old browsers are not supported by your application.

You can empty a set in one call. The method returns true if any elements are removed from the set model object.

setModel.clear(); // returns false, alpha and beta removed above.

If the call to clear does delete elements from the set, all "change" event listeners are passed an event object with deletedTargets just as for the delete method.

Another interesting feature of a set model object is that it observes its elements (for all elements that implement the event target interface) and when an element dispatches a "destroy" event then the element is automatically removed from the set model object. The set model object then dispatches a "change" event with a deletedTargets property just as for the delete method.

A set model object has some other handy methods.

setModel.add(alpha, beta);

setModel.toArray(); // returns [alpha, beta] or [beta, alpha]

setModel.forEach(function(element) {
    alert(element.name);
});

setModel.every(function(element) {
    return element.name.length > 4;
}); // returns false

setModel.some(function(element) {
    return element.name.length > 4;
}); // returns true

setModel.reduce(function(accumulator, element) {
    return accumulator + element.name.length;
}, 0); // returns 9

The order of the elements returned by toArray and the order of iteration of the other methods is undefined as a set is an unordered collection. Do not depend on any ordering that the current implementation uses.

A particularly useful pattern is using maria.SetModel as the "superclass" of your application's collection model. The following example shows how this can be done at a low level for a to-do application. See maria.SetModel.subclass for a more compact way to accomplish the same.

checkit.TodosModel = function() {
    maria.SetModel.apply(this, arguments);
};
checkit.TodosModel.superConstructor = maria.SetModel;
checkit.TodosModel.prototype = maria.create(maria.SetModel.prototype);
checkit.TodosModel.prototype.constructor = checkit.TodosModel;
checkit.TodosModel.prototype.isAllDone = function() {
    return (this.size > 0) &&
           this.every(function(todo) {
               return todo.isDone();
           });
};
checkit.TodosModel.prototype.isAllUndone = function() {
    return this.every(function(todo) {
               return !todo.isDone();
           });
};
checkit.TodosModel.prototype.markAllDone = function() {
    this.forEach(function(todo) {
        todo.setDone(true);
    });
};
checkit.TodosModel.prototype.markAllUndone = function() {
    this.forEach(function(todo) {
        todo.setDone(false);
    });
};
checkit.TodosModel.prototype.deleteDone = function() {
    var doneTodos = [];
    this.forEach(function(todo) {
        if (todo.isDone()) {
            doneTodos.push(todo);
        }
    });
    this['delete'].apply(this, doneTodos);
};

Another feature of set model objects is that events dispatched on elements of the set model object bubble up and are dispatched on the set model object. This makes it possible to observe only the set model object and still know when elements in the set are changing, for example. This can complement well the flyweight pattern used in a view.

Source:
  • maria.js, line 2092

Extends

Members

<static> superConstructor

Properties:
Name Type Description
maria.SetModel.superConstructor
Source:
  • maria.js, line 2102

<readonly> size

The number of elements in the set.

Inherited From:
Source:
  • maria.js, line 1348

Methods

<static> subclass()

A function that makes subclassing maria.SetModel more compact.

The following example creates a checkit.TodosModel constructor function equivalent to the more verbose example shown in the documentation for maria.SetModel.

maria.SetModel.subclass(checkit, 'TodosModel', {
    properties: {
        isAllDone: function() {
            return (this.size > 0) &&
                   this.every(function(todo) {
                       return todo.isDone();
                   });
        },
        isAllUndone: function() {
            return this.every(function(todo) {
                       return !todo.isDone();
                   });
        },
        markAllDone: function() {
            this.forEach(function(todo) {
                todo.setDone(true);
            });
        },
        markAllUndone: function() {
            this.forEach(function(todo) {
                todo.setDone(false);
            });
        },
        deleteDone: function() {
            var doneTodos = [];
            this.forEach(function(todo) {
                if (todo.isDone()) {
                    doneTodos.push(todo);
                }
            });
            this['delete'].apply(this, doneTodos);
        }
    }
});
Source:
  • maria.js, line 3378

['delete'](item) → {boolean}

Takes multiple arguments each to be deleted from the set.

setModel'delete' setModel['delete'](item1, item2) ...

If the set is modified as a result of the delete request then a change event is dispatched on the set model object. If all of the arguments were already not in the set then this event will not be dispatched.

Parameters:
Name Type Description
item Object

The item to be removed from the set.

Source:
  • maria.js, line 2173
Returns:

True if the set was modified. Otherwise false.

Type
boolean

add(item) → {boolean}

Takes multiple arguments each to be added to the set.

setModel.add(item1) setModel.add(item1, item2) ...

If the set is modified as a result of the add request then a change event is dispatched on the set model object. If all of the arguments are already in the set then this event will not be dispatched.

Parameters:
Name Type Description
item Object

The item to be added to the set.

Source:
  • maria.js, line 2130
Returns:

True if the set was modified. Otherwise false.

Type
boolean

addEventListener(type, listener)

If the listener is an object then when a matching event type is dispatched on the event target, the listener object's handleEvent method will be called.

If the listener is a function then when a matching event type is dispatched on the event target, the listener function is called with event target object set as the this object.

One listener (or type/listener pair to be more precise) can be added only once.

et.addEventListener('change', {handleEvent:function(){}});
et.addEventListener('change', function(){});
Parameters:
Name Type Description
type string

The name of the event.

listener Object | function

The listener object or callback function.

Inherited From:
Source:
  • maria.js, line 72

addParentEventTarget(parent)

When an event is dispatched on an event target, if that event target has parents then the event is also dispatched on the parents as long as bubbling has not been canceled on the event.

One parent can be added only once.

var o = new evento.EventTarget();
et.addParentEventTarget(o);
Parameters:
Name Type Description
parent EventTarget

A parent to call when bubbling an event.

Inherited From:
Source:
  • maria.js, line 128

clear() → {boolean}

Deletes all elements of the set.

If the set is modified as a result of this clear request then a change event is dispatched on the set model object.

Source:
  • maria.js, line 2206
Returns:

True if the set was modified. Otherwise false.

Type
boolean

destroy()

When a model is destroyed, it dispatches a destroy event to let listeners (especially containing maria.SetModel objects) that this particular model is no longer useful/reliable.

Inherited From:
Source:
  • maria.js, line 1914

dispatchEvent(event)

The event.type property is required. All listeners registered for this event type are called with event passed as an argument to the listeners.

If not set, the event.target property will be set to be this event target.

The evt.currentTarget will be set to be this event target.

Call evt.stopPropagation() to stop bubbling to parents.

et.dispatchEvent({type:'change'});
et.dispatchEvent({type:'change', extraData:'abc'});
Parameters:
Name Type Description
event Object

The event object to dispatch to all listeners.

Inherited From:
Source:
  • maria.js, line 184

every(callbackfn, thisArg) → {boolean}

Calls callbackfn for each element of the set.

var one = {value: 1};
var two = {value: 2};
var three = {value: 3};
var set = new hormigas.ObjectSet(one, two, three);
set.every(function(element) {
    return element.value < 2;
}); // false
Parameters:
Name Type Argument Description
callbackfn function

The function to call for each element in the set.

thisArg Object <optional>

The object to use as the this object in calls to callbackfn.

Inherited From:
Source:
  • maria.js, line 1523
Returns:

true if callbackfn returns a truthy value for all elements in the set. Otherwise false.

Type
boolean

forEach(callbackfn)

Calls callbackfn for each element of the set.

var alpha = {value: 0};
var beta = {value: 1};
var gamma = {value: 2};
var set = new hormigas.ObjectSet(alpha, beta, gamma);
set.forEach(function(element) {
    console.log(element.value);
});
Parameters:
Name Type Description
callbackfn function

The function to call for each element in the set.

Inherited From:
Source:
  • maria.js, line 1495

handleEvent(event)

If a member of the set fires a destroy event then that member must be deleted from this set. This handler will do the delete.

Parameters:
Name Type Description
event Object

The event object.

Source:
  • maria.js, line 2232

has(element)

Is a particular object in the set or not?

var alpha = {};
var beta = {};
var set = new hormigas.ObjectSet(alpha);
set.has(alpha); // true
set.has(beta); // false
Parameters:
Name Type Description
element Object

The item in question.

Inherited From:
Source:
  • maria.js, line 1373
Returns:

true if element is in the set. Otherwise false.

reduce(callbackfn, initialValue) → {*}

Calls callbackfn for each element of the set.

For the first call to callbackfn, if initialValue is supplied then initalValue is the first argument passed to callbackfn and the second argument is the first element in the set to be iterated. Otherwise the first argument is the first element to be iterated in the set and the second argument is the next element to be iterated in the set.

For subsequent calls to callbackfn, the first argument is the value returned by the last call to callbackfn. The second argument is the next value to be iterated in the set.

var one = {value: 1};
var two = {value: 2};
var three = {value: 3};
var set = new hormigas.ObjectSet(one, two, three);
set.reduce(function(accumulator, element) {
    return {value: accumulator.value + element.value};
}); // {value:6}
set.reduce(function(accumulator, element) {
    return accumulator + element.value;
}, 4); // 10
Parameters:
Name Type Description
callbackfn function

The function to call for each element in the set.

initialValue *

The optional starting value for accumulation.

Inherited From:
Source:
  • maria.js, line 1596
Returns:

The value returned by the final call to callbackfn.

Type
*

removeEventListener(type, listener)

Removes added listener matching the type/listener combination exactly. If this combination is not found there are no errors.

var o = {handleEvent:function(){}};
et.removeEventListener('change', o);
et.removeEventListener('change', fn);
Parameters:
Name Type Description
type string

The name of the event.

listener Object | function

The listener object or callback function.

Inherited From:
Source:
  • maria.js, line 99

removeParentEventTarget(parent)

Removes parent added with addParentEventTarget. If the parent is not found, there are no errors.

var o = {handleEvent:function(){}};
et.removeParentEventTarget(o);
Parameters:
Name Type Description
parent EventTarget

The parent to remove.

Inherited From:
Source:
  • maria.js, line 154

some(callbackfn, thisArg) → {boolean}

Calls callbackfn for each element of the set.

var one = {value: 1};
var two = {value: 2};
var three = {value: 3};
var set = new hormigas.ObjectSet(one, two, three);
set.some(function(element) {
    return element.value < 2;
}); // true
Parameters:
Name Type Argument Description
callbackfn function

The function to call for each element in the set.

thisArg Object <optional>

The object to use as the this object in calls to callbackfn.

Inherited From:
Source:
  • maria.js, line 1553
Returns:

true if callbackfn returns a truthy value for at least one element in the set. Otherwise false.

Type
boolean

toArray() → {Array}

Convert the set to an array.

Inherited From:
Source:
  • maria.js, line 1468
Returns:

The elements of the set in a new array.

Type
Array