When I click this button, an object is created and added to the array which is reflected in UI. Next when I click this button again I get an error "Cannot read property 'push' of undefined". What could possibly be the issue? Since the context seems fine otherwise it wouldn't have called the appropriate function in Rule class.
html code
<div data-bind="with: formatterVM">
<div data-bind="with: currentRule">
<ul data-bind="foreach: conditions">
<li data-bind="html: x"></li>
<li data-bind="html: y"></li>
</ul>
<button data-bind="click: addCondition">Click</button>
</div>
</div>
JS/Knockout code
function ReportsVM() {
self = this
self.formatterVM = new FormatterVM()
}
function FormatterVM(){
self = this
self.rules = ko.observableArray()
self.currentRule = ko.observable(new Rule())
}
function Rule(){
self = this
self.conditions = ko.observableArray()
self.addCondition = function(){
self.conditions.push(new Condition(2,3))
}
}
function Condition(x,y){
self = this
self.x = ko.observable(x)
self.y = ko.observable(y)
}
// Activates knockout.js
ko.applyBindings(new ReportsVM());
Working JSFiddle https://jsfiddle.net/etppe937/
Update
It was an issue with the scope of the self
variable. We need to use var
keyword in order to not let the variable have a global scope. JSFiddle has been updated.