4

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

1

1 Answer 1

5

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');
        }
    };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.