-
-
Save clinuz/3389dbdd3a38dd8fc143 to your computer and use it in GitHub Desktop.
Example of custom merge strategy for integrating fetched data into an enyo.Collection that may have records that already exist in the shared store (with another enyo.Collection) as per the discussion: http://forums.enyojs.com/discussion/1830/how-to-merge-records-from-different-collections.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enyo.kind({ | |
name: "sample.Collection", | |
kind: "enyo.Collection", | |
// this may not be preferred but for example we overload fetch to always default | |
// to the new _reuseOrAdd_ strategy unless specified | |
fetch: function (opts) { | |
opts = opts || {}; | |
opts.strategy = opts.strategy || "reuseOrAdd"; | |
// ensure we're passing our new arguments | |
this.inherited(arguments, [opts]); | |
}, | |
// we use a custom merge strategy to check if the record exists in the store | |
// and reuse it if it does | |
reuseOrAdd: function (records) { | |
// we need to be able to figure out what the primary key is that will be | |
// used to check uniqueness in the store, since you may already know this | |
// you could hardcode it in | |
var store = this.store, | |
proto = this.model.prototype, | |
pk = proto.primaryKey; | |
// we still have to check to make sure this is in an array form | |
// so it is usable directly with a single record as well | |
if (records) { | |
records = enyo.isArray(records)? records: [records]; | |
for (var i=0, data, record; (data=records[i]); ++i) { | |
// we use the _findLocal_ method of the store to see if a record | |
// with these keys already exists | |
record = store.findLocal(this.model, data); | |
if (record) { | |
// if it does we replace the entry with the existing one | |
records[i] = record; | |
// optionally you could update the value if that was something you wanted | |
// to do as well such as... | |
record.setObject(data); | |
} | |
} | |
// now that we know we either have new records or existing records | |
// and we want to be able to safely call this whether adding or merging | |
// with existing data we let the default merge now do its thing | |
this.merge(records); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment