knockout / knockout

Knockout makes it easier to create rich, responsive UIs with JavaScript
http://knockoutjs.com/
Other
10.44k stars 1.52k forks source link

Modernizing viewmodels with JavaScript decorators #2526

Closed BrightSoul closed 4 years ago

BrightSoul commented 4 years ago

Hello there. First of all: thank you for supporting this project throughout all this years. I'm still using it today for new component-based applications. I had no problem whatsover making it work with ES6 classes and Babel.

Now, for various reasons (e.g. colleagues nagging) I wanted to modernize my viewmodels and templates. This a short list of my objectives:

Here's what my ViewModel would look like:

class PersonViewModel {
    @observable
    firstName;

    @observable
    lastName;

    @computed
    fullName() {
        return this.firstName + " " + this.lastName;
    }

    @subscribe('fullName')
    onFullNameChanged (fullName) {
        console.log('FullName changed', fullName);
    };

    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

The @observable and @computed decorators would change the descriptor of the class fields and methods by defining getter and setter wrappers that would proxy the underlying observables. I already wrote some code to test this idea and it's showing promising results. Of course, this would add a bit of overhead but I'm willing to pay the cost in order to get a more concise and declarative syntax.

Before I proceed further, do you have opinions about this? Any gotchas I should be aware of? Things get a bit more difficult with observableArrays since I also have to proxy array methods but nothing to be really scared about.

Thanks Moreno

BrightSoul commented 4 years ago

Nevermind, I just found out this project that does this very same thing :D https://github.com/gnaeus/knockout-decorators