Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Last active September 15, 2015 02:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valerysntx/86a0f92f579e1326f9f6 to your computer and use it in GitHub Desktop.
Save valerysntx/86a0f92f579e1326f9f6 to your computer and use it in GitHub Desktop.
ViewModelBase observable properties wrapper class
(function(ko){
ko.ViewModel = function ViewModel(){
Object.getOwnPropertyNames(this)
.map(name => ({
name,
desc: Object.getOwnPropertyDescriptor(this, name)
}))
.filter(o => o.desc.configurable)
.forEach(o => {
let obs = ko.observable(this[o.name]);
Object.defineProperty(this, o.name, {
enumerable: true,
configurable: true,
get: obs,
set: obs
});
});
let proto = Object.getPrototypeOf(this);
Object.getOwnPropertyNames(proto)
.map(name => ({
name,
desc: Object.getOwnPropertyDescriptor(proto, name)
}))
.filter(o => o.desc.configurable)
.filter(o => 'get' in o.desc)
.forEach(o => {
let comp = ko.pureComputed({
read: o.desc.get.bind(this),
write: o.desc.set ? o.desc.set.bind(this) : null
});
Object.defineProperty(this, o.name, {
enumerable: true,
configurable: true,
get: comp,
set: o.desc.set ? comp : undefined
});
});
}
ko.ViewModel.prototype.with = function(obs){
return ko.pureComputed(() => obs());
};
})(ko);
/*
usage with ES6
class ViewModel extends ViewModelBase {
this.name = '';
constructor(_name = "stranger"){
this.name = _name;
this.with(()=> this.name).subscribe((value)=> console.log( "Hello! " + value ) );
super(); //here the esx magic, e.g. 'this.name' became observable property transparent for syntax...
}
get Greeting = function() {
return this.name + ", howd'y?";
}
}
}
*/
@valerysntx
Copy link
Author

It will not compile, since having undefined this reference in ctor, which is forbidden, according to the latest es6 document drafts. There is possible ways to fix issue, trying to keep same expressional level, wrapping properties transparently within inherited class ctor.

  • move functionality out of ctor into own function method
  • decouple approach independently, using es6 generics
  • use property accessor instance as parameter to base class .ctor, having default to be set as es6 default parameter expression
  • extend 'with' fiction prototype, to implement or reference actual wrapper functionality
    (which seems as the most naive but powerful approach, when done using es6 arrow functions, which is easy to implement )

@vmysla
Copy link

vmysla commented Sep 15, 2015

@vmysla
Copy link

vmysla commented Sep 15, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment