简体   繁体   中英

TypeScript Class as ViewModel using Knockout?

I am currently creating my Knockout ViewModel like this,

function MyViewModel() {
    var self = this;

    self.MyObservable = ko.observable();

}

ko.applyBindings(new MyViewModel());

Is there a way to use this TypeScript Class as a ViewModel?

class MyViewModel {

}

I know in the end the TSC generates a function anyway but to stick with the TypeScript convention I would just like to know if it is possible?

Thanks

Yeah, in many of my projects I use TypeScript for my KO viewmodels. The following TypeScript:

class MyViewModel {
    MyObservable = ko.observable();
    MyComputed = ko.computed(() => {
        return this.MyObservable() * 2;
    })
}

Renders the following valid viewmodel:

var MyViewModel = (function () {
    function MyViewModel() {
        var _this = this;
        this.MyObservable = ko.observable();
        this.MyComputed = ko.computed(function () {
            return _this.MyObservable() * 2;
        });
    }
    return MyViewModel;
})();

Be careful when using functions though; the following TypeScript function:

MyFunction() {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
}

Will render:

MyViewModel.prototype.MyFunction = function () {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
};

Meaning you might run into scope problems with this when you're using this function directly in your binding for example ( data-bind="click: MyFunction" would fail).

To prevent these scope issues, you should be declaring the functions in your viewmodels as lambas:

MyFunction = () => {
    if (this.MyComputed() > 4) {
        alert('Higher than 4');
    }
}

Renders:

    this.MyFunction = function () {
        if (_this.MyComputed() > 4) {
            alert('Higher than 4');
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM