Skip to content

Instantly share code, notes, and snippets.

@crobinson42
Last active November 7, 2018 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crobinson42/f24c3c4dda920cafde97cf28f2c17494 to your computer and use it in GitHub Desktop.
Save crobinson42/f24c3c4dda920cafde97cf28f2c17494 to your computer and use it in GitHub Desktop.
JS-Data - Proxy context issue demo (https://stackoverflow.com/posts/53197772)
import { DataStore, Mapper } from 'js-data'
class ExtendedDataStore extends DataStore {
as(name) {
const props = {}
// const original = super.as(name)
const mapper = this.getMapper(name)
const self = this
// if "this" is passed instead of "self" the downstream methods fail without straightforward Error stacktrace
// but when using "self" as the 1st arguement, things work normal, as expected
const proxy = new Proxy(self, {
get: function(target, prop, receiver) {
// first try the prop on the DataStore
if (target[prop]) return (...args) => target[prop].apply(self, [name, ...args])
// then try the mapper because we have custom props on mapper classes
return mapper[prop]
},
})
return proxy
}
}
const Store = new ExtendedDataStore()
Store.defineMapper('user')
Store.User = Store.as('user') // make a short-hand for User so we don't have to do `Store.getMapper('user').updateEmail(...)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment