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> 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());
};
})();
You could use a function literal so that you can pass the parent object to your addToCase function, but that seems like working around the problem rather than solving it.