Closed jamesladd closed 11 years ago
Essentially I want a find(element) or find(id)
There isn't anything in particular for what you describe. There is a setModel.toArray()
method. You can look through the results returned by that.
maria.SetModel.prototype.find = function(fn) {
var elements = this.toArray();
for (var i = 0, ilen = elements.length; i < ilen; i++) {
var element = elements[i];
if (fn(element) {
return element;
}
}
};
Using this function frequently would be an inefficient way to update all the elements. O(n^2)
If you have id attributes on these elements you could do much better to update all the elements in the set.
myApp.MySetModel.prototype.fromJSON = function(json) {
var elements = this.toArray();
var elementsMap = {};
for (var i = 0, ilen = elements.length; i < ilen; i++) {
var element = elements[i];
elementsMap[element.getId()] = element;
}
var toAdd = [];
for (var i = 0, ilen = json.length; i < ilen; i++) {
var elementJSON = json[i];
if (elementMap[elementJSON.id]) {
elementMap[elementJSON.id].fromJSON(elementJSON); // an update, which could dispatch a "change" event.
}
else {
toAdd.push(myApp.MyModel.createFromJSON(elementJSON));
}
}
this.add.apply(this, toAdd); // dispatches only one change event on the set for all items added.
};
This approach using the id is O(n)
Please reopen if you still have more questions.
Marias set allows me to say set.has(element) and it returns true/false. However, how can I get the existing element?
The situation I'm trying to deal with is a refresh of data from the server. If the element is new I add it but if it exists then I want to update it.