Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript member method passed into KO click binding ends up with "wrong" scope

I'm writing a single page application using KnockoutJS and Typescript.

The issue is this, I have a MainViewModel with the method:

public addToCase(email) {
    this.addToCaseVM.setEmail(email, this.getEmailBody());
};

I have an email view in my page that has an "Add To Case" button that is bound in html like this:

<a class="btn btn-info" data-bind="click: $root.addToCase" data-toggle="modal" href="#addToCaseModal"><i class="icon-plus-sign"></i>&nbsp;Add To Existing Case</a>

Where $root is my MainViewModel. When this button is clicked the 'email' parameter of the function is the correct selected email in the MainViewModel but the scope of the function is also the EmailViewModel, not the MainViewModel on which the function is defined.

I understand why this happens, I'm interested in how to solve the particular issue in Typescript since I can't declare a pointer to the MainViewModel instance like I would in pure javascript:

var MainViewModel = (function(){ 
    var self = this; 

    this.addToCase = function(email) {
        self.addToCaseVM.setEmail(email, self.getEmailBody());
    };
})();
like image 990
Andrew Benton Avatar asked Nov 05 '12 17:11

Andrew Benton


1 Answers

My solution to this was to declare class method and leave it empty untill constructor is called, then define method body. This way method will be scoped correctly.

class MainViewModel {

    addToCase: (email) => void;

    constructor() {
        this.addToCase = (email) => {
            this.addToCaseVM.setEmail(email, this.getEmailBody());
        };
    }
}
like image 61
Slawek Avatar answered Sep 20 '22 01:09

Slawek