-
Notifications
You must be signed in to change notification settings - Fork 0
inheritance.md
Blake Friedman edited this page Feb 26, 2016
·
1 revision
If we want to change basic behaviour about how our data is stored in JSONifier, inheritance is a good way to go about this.
I want to store JSON objects that are particular to URL path. We can achieve this by munging the namespaces, but I'd prefer to have a clearly defined API for my users.
The key things to modify are our constructor and the state getters and setters:
class ThePath extends JSONifier {
constructor(state, ops) {
super(state, ops);
this.__state = {};
// Use old path to sherpa in inherited data
this.path = this.path || '/';
this.state = this.__tmp;
// Use new path for all that follows
this.path = ops ? ops.path || '/' : '/';
}
get state() {
return this.path
? this.__state[this.path]
: this.__tmp
;
}
set state(s) {
return this.path
? this.__state[this.path] = s
: this.__tmp = s
;
}
build(path) {
this.path = path || '/';
return super.build();
}
}
So our new API is quite exciting, we can now inherit data for multiple paths, but restrict to a particular path at build time:
let base = new ThePath({path: '/login'})
.add({
'username', 'blakef'
'attempts', function* mockAttempts() { let count = 0; while(true) yield ++count; }
});
let fin = new ThePath({path: '/authenticated'})
.add({ 'message': 'welcome user'});
> fin.build('/login').next().value
{ 'username': 'blakef', 'attempts': 0 }
> fin.build('/authenticated').next().value
{ 'message': 'welcome user' }
So we're able to gradually build up more complexity, but still remain concise.