Implement #getItems(match) on Project and Item as a simple and efficient query interface.

This commit is contained in:
Jürg Lehni 2013-10-19 12:27:13 +02:00
parent 49a8ea24af
commit 4fb6a5d949
2 changed files with 65 additions and 4 deletions

View file

@ -1234,6 +1234,56 @@ var Item = Base.extend(Callback, /** @lends Item# */{
return this._parent ? this._parent.isInserted() : false;
},
// DOCS: Item#getItems
getItems: function(match) {
var children = this.children,
items = [];
for (var i = 0, l = children && children.length; i < l; i++) {
var child = children[i];
if (child.matches(match))
items.push(child);
items.push.apply(items, child.getItems(match));
}
return items;
},
// DOCS: Item#matches
matches: function(match) {
// matchObject() is used to match against objects in a nested manner.
// This is useful for matching against Item#data.
function matchObject(obj1, obj2) {
for (var i in obj1) {
if (obj1.hasOwnProperty(i)) {
var val1 = obj1[i],
val2 = obj2[i];
if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
if (!matchObject(val1, val2))
return false;
} else if (!Base.equals(val1, val2)) {
return false;
}
}
}
return true;
}
for (var key in match) {
if (match.hasOwnProperty(key)) {
var value = this[key],
compare = match[key];
if (compare instanceof RegExp) {
if (!compare.test(value))
return false;
} else if (Base.isPlainObject(compare)) {
if (!matchObject(compare, value))
return false;
} else if (!Base.equals(value, compare)) {
return false;
}
}
}
return true;
},
equals: function(item) {
// Note: We do not compare name and selected state.
return item === this || item && this._class === item._class

View file

@ -154,6 +154,15 @@ var Project = PaperScopeItem.extend(/** @lends Project# */{
return this._index;
},
// DOCS: Project#getItems
getItems: function(match) {
var layers = this.layers,
items = [];
for (var i = 0, l = layers.length; i < l; i++)
items.push.apply(items, layers[i].getItems(match));
return items;
},
/**
* The selected items contained within the project.
*
@ -202,16 +211,18 @@ var Project = PaperScopeItem.extend(/** @lends Project# */{
* Selects all items in the project.
*/
selectAll: function() {
for (var i = 0, l = this.layers.length; i < l; i++)
this.layers[i].setFullySelected(true);
var layers = this.layers;
for (var i = 0, l = layers.length; i < l; i++)
layers[i].setFullySelected(true);
},
/**
* Deselects all selected items in the project.
*/
deselectAll: function() {
for (var i in this._selectedItems)
this._selectedItems[i].setFullySelected(false);
var selectedItems = this._selectedItems;
for (var i in selectedItems)
selectedItems[i].setFullySelected(false);
},
/**