如何修复Knockout.js中的未定义属性错误 [英] How to fix undefined property error in knockoutjs

查看:88
本文介绍了如何修复Knockout.js中的未定义属性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数时候,我会在淘汰赛中得到未定义"属性的错误.我在 stackoverflow答案上找到了解决方案.它对于简单的绑定是有效的,但是我的问题是我将如何像我尝试过的那样将这种技术用于"foreach"绑定

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

在此处演示

下面的代码不起作用

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都一样:

Js for both is same like:

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

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

ko.applyBindings......

推荐答案

想象一下您的模型"是一个函数.在html中绑定时,您只能访问模型的局部变量.模型本身不可见,因为这超出了您的范围.映射是模型中的变量,这就是为什么您只需编写foreach: mappings即可访问它的原因. model不是模型的一部分,它是模型...希望对您有所帮助.

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.

此外,当您编写foreach: mappings时,您会进入一个foreach循环,这就是为什么您不编写mappings.PropertyName而只编写PropertyName

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

这篇关于如何修复Knockout.js中的未定义属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆