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());
};
})();
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());
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With