Pergunta

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.

Foi útil?

Solução

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/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top