I am trying to get to grips with knockout.js, but I seem to be running into a javascript quirck I am not aware of.
Html
<ul data-bind="foreach: someList">
<li data-bind="text: number"></li>
</ul>
Javascript
function NestedViewModel(number) {
self = this;
self.number = ko.observable(number);
}
function ViewModel() {
self = this;
self.someList = [];
for (i=0;i<10;i++) {
var vm = new NestedViewModel(i);
self.someList.push(vm);
}
}
ko.applyBindings(new ViewModel());
When I run this code, nothing happens. The console shows an error:
Uncaught TypeError: Cannot read property 'push' of undefined
When I remove the self = this; line from the NestedViewModel, and I replace self.number by this.number, everything works fine! I have no clue what javascript is doing under the hood here... Does somebody have an explanation for this? And a solution?