Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - How to fix undefined property error in knockoutjs

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......
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...