0

My TypeScript

export class CustomerUIModel implements CustomerIntrerfaces.ICustomerUI {

    public customers: KnockoutObservableArray<CustomerIntrerfaces.ICustomer>;
    service: CustomerIntrerfaces.ICustomerService;



    constructor(svc: CustomerIntrerfaces.ICustomerService, data: CustomerIntrerfaces.ICustomer[]) {
        this.service = svc;
        this.customers = ko.observableArray(data);
    }

    public AddCustomer(elem: CustomerIntrerfaces.ICustomer): void {
        this.service.Insert(elem)
            .then(cRes => {
                this.customers.push(elem);
            })
            .catch(r => {
                alert(r.message);
            });
    }
}}

My HTML:

        <tbody data-bind="foreach: customers">
        <tr>
            <td><input type="text" class="form-control" size="5" data-bind="value: CustomerID" /></td>
            <td><input type="text" class="form-control" data-bind="value: CompanyName" /></td>
            <td><input type="text" class="form-control" data-bind="value: ContactName" /></td>
            <td><input type="text" class="form-control" data-bind="value: Country" /></td>
            <td>
                <input type="button" class="form-control" value="Insert" data-bind='click: $root.AddCustomer' />
                <input type="button" class="form-control" value="Delete" data-bind='click: $root.DeleteCustomer' />
            </td>
        </tr>
    </tbody>

When I click on "Insert" I get into AddCustomer() but this.service is NULL as well as customers. Moreover,"this" has a CustomerIntrerfaces.ICustomer, not a CustomerIntrerfaces.ICustomerService as I expect. How can I have this fixed?

user216652
  • 567
  • 5
  • 11

1 Answers1

1

It looks like Knockout is not calling the AddCustomer method with the this context you want. See this thread. You can force the this context to be your CustomerUIModel object by binding the method like this:

public AddCustomer = (elem: CustomerIntrerfaces.ICustomer): void => {
    this.service.Insert(elem)
        .then(cRes => {
            this.customers.push(elem);
        })
        .catch(r => {
            alert(r.message);
        });
}

See this FAQ for more information about the general problem.

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75