Last active
September 15, 2015 02:23
-
-
Save valerysntx/86a0f92f579e1326f9f6 to your computer and use it in GitHub Desktop.
ViewModelBase observable properties wrapper class
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
(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?"; | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
(which seems as the most naive but powerful approach, when done using es6 arrow functions, which is easy to implement )