I am using TypeScript
. I am trying to bind the response from rest API to a variable in a ViewModel
like below:
export class TestListViewModel {
public personItems: KnockoutObservableArray<Person>;
constructor() {
this.personItems = ko.observableArray([]);
this.person1 = new Person();
this.person1.name = ko.observable<string>("Test 1");
this.person1.ssnId = ko.observable<string>("1234");
this.personItems.push(this.person1);
//If i put a debugger here and see the "this.personItems()" in console
//I can see 1 object in personItems
$.get("https://somerestapi/api/TestLists",
(data: any) => {
for (var index in data) {
this.person1 = new Person();
this.person1.name = ko.observable<string>(data[index].name);
this.person1.ssnId = ko.observable<string>(data[index].ssnId);
this.personItems.push(this.person1);
//If i put a debugger here and see the "this.personItems()" in console
**//Now i am getting error "Uncaught TypeError: this.personItems is not a function"**
//If i do only "this.personItems" it is giving as "Undefined"
}
});
} //end of constructor
} //end of class
Please see my comments in the code. When I am giving the data to personItems
variable in constructor then I can see the data in the variable. But when I am doing the same in success cal back of $.get
then data is not getting added to personItems
variable. Why?
Could some one please help me what is wrong with my code. Thanks.
It is the scoping problems with javascript.
Can you try following code?
Is this the entire code for the class? Is
personItems
accessed anywhere outside of the constructor? I would guess that there is something else that is manipulatingpersonItems
after$get
is called and before it returns, and setting its size to 0.