Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Last active September 15, 2015 02:23
Show Gist options
  • 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?";
}
}
}
*/
@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