Binding Jagged Array with knockout

青春壹個敷衍的年華 提交于 2019-12-11 10:38:20

问题


I have having problem to binding jagged array in knockout-js. I have search a lot but could not found any thing. Let make a simple example,

<div data-bind="foreach: items">
<div  data-bind="style: { textAlign: align, backgroundColor:  bgColor, fontFamily: fontFamily, fontSize: size, color: color }, text: title"></div>
</div>

and here is the my array,

var items = [{
                    title: 'A',
                    align: 'right',
                    fontFamily: 'helvetica',
                    color: '#777777',
                    bgColor: '#ffffff'
            }, 
            {
                    title: 'A',
                    align: 'right',
                    size: 'large',
                    fontFamily: 'helvetica'
            }
            {
                    size: 'large',
                    fontFamily: 'helvetica',
                    color: '#777777'
            }]

Clearly sometime some property(ies) are missing? So I get * is not defined* error. How to handle this situation.


回答1:


you have two options. You can make sure your ViewModels aren't jagged. This is accomplished well by using the knockout mapping plugin against your model and having it use a constructor of your type. this way you can even define defaults

the other option is to reference the values off of the $data context. IE:

<div  data-bind="style: { textAlign: $data.align, backgroundColor:  $data.bgColor, fontFamily: $data.fontFamily, fontSize: $data.size, color: $data.color }, text: $data.title"></div>

fiddle: http://jsfiddle.net/drdamour/Xp9Er/



来源:https://stackoverflow.com/questions/14535102/binding-jagged-array-with-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!