How to fix undefined property error in knockoutjs

2019-09-19 23:52发布

问题:

Most of the time i get some error for 'undefined' property in knockout. I found a solution for the same on stackoverflow answer. It is effective for simple binding, but my question is that how would i use this technique for 'foreach' binding like i have tried like

Demo here

below code is not working

<table>
  <tbody data-bind="foreach: model.mappings">
    <tr>
     <td>
    <select data-bind="options:mappings.variableList, optionsText:'Key',optionsValue:'Value', value:mappings.selectedVariable>
    </select>
   </td></tr></tbody></table>

But below code is working

<table>
  <tbody data-bind="foreach:mappings">
    <tr>
     <td>
    <select data-bind="options:variableList, optionsText:'Key',optionsValue:'Value', value:selectedVariable>
    </select>
   </td></tr></tbody></table>

Js for both is same like:

var list = //some array
var arr =// [{variableList : list}];

var model={
mappings:ko.observableArray(arr)
}

ko.applyBindings......

回答1:

Imagine your "model" being a function. When binding in html, you are able to access only local variables of model. Model itself is not visible because that is out of your scope. Mappings is a variable in model and that's why you can access it by just writing foreach: mappings. model is not part of model, it is model... Hope this helps.

Also, when you write foreach: mappings then you kind-of enter a foreach loop so that is why you don't write mappings.PropertyName and instead just write PropertyName

edit: my comment on your post was completely wrong so I deleted it