Poul K. Sørensen
Poul K. Sørensen

Reputation: 17530

Was it not the intention that TypeScript would handle the this scope for me?

I am working with knockout and TypeScript .

I get an error on this:

AppViewModel.prototype.setActive = function (data, event) {
            this.active(data);
        };

from this TypeScript file:

export class AppViewModel {

    ///Properties
    projects = projects;
    error = ko.observable();
    active = ko.observable();
    //setActive: (data,e)=>void;
    ///Constructor
    constructor()
    {
        this.active = ko.observable();
        DataContext.getProjects(this.projects, this.error);


    }

    isActive(data)
    {
        return this.active() == data;
    }
    setActive(data, event) {

        this.active(data);
    }
}

Object # has no method 'active', it is bound like this:

<li class="nav-header">Projects</li>
            <!-- ko foreach: projects -->
            <li class="">
                <a href="#" data-bind="click: $parent.setActive, css: { active: ($parent.isActive($data)) }">
                    <i class="icon-pencil"></i>
                    <span style="padding-right: 15px;" data-bind="text: title"></span>
                </a>
            </li>
            <!-- /ko --> 

$Parent should be the AppViewModel. it works until I click the link.

I am not 100% sure if the error is related to something I do not understand with binding or its the typescript generated functions and this is not proper handled.

this in a prototype function refer to the object itself? or the function scope?

Upvotes: 2

Views: 420

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

TypeScript doesn't attempt to guess which this context you wanted. If you want setActive to always use the class instance as the this context, you can bind it in the constructor:

export class AppViewModel {
    ...
    constructor() {
        this.active = ko.observable();
        DataContext.getProjects(this.projects, this.error);
        this.setActive = this.setActive.bind(this);
    }
    ...
}

Upvotes: 5

Related Questions