0

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.

  • [declaring-variables-without-var](https://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword) – Jason Spake Dec 07 '17 at 18:57
  • Can you be more specific with your answer? Which variables need to be declared with 'var' keyword? – Parthenophobic Sallu Dec 07 '17 at 18:58
  • Well all of them should be, but in your example there's only one undeclared variable, and that's "self". – Jason Spake Dec 07 '17 at 19:00
  • if your code is trying to access the `property` push instead of trying to leverage the `function` push, then `conditions` is probably not the type you are expecting it to be. And actually, looks like `conditions` is `undefined` to start with, therefore there is no accessible `function` called `push` on that _object_. – blaze_125 Dec 07 '17 at 19:02
  • @JasonSpake Great! This has solved my issue. Thanks for your help! – Parthenophobic Sallu Dec 07 '17 at 19:04

0 Answers0