开发者

How to use the style data bindings?

I'm having difficulties getting the style binding working in KnockoutJS.

<script id="avatarTemplate" type="text/x-jquery-tmpl">
  <div id="avatar_${id}" class="avatar" data-bind="style: 
    { background: s, width: '50px', hei开发者_Python百科ght: '85px', left: (x + 'px'), top: 
    (y + 'px') }">${s}, ${x}, ${y}</div> 
</script> 

<div data-bind="template: { name: 'avatarTemplate', foreach: avatars }"></div> 

The result of rendering this template is:

<div id="avatar_1" class="avatar" style="width: 50px; height: 85px;">avatar.png, 0, 0</div> 

Can anyone help me figure out why all styles which are dependent on the view model do not show up?


If x and y are observables, then you need to specify it like this:

<div id="avatar_${id}" class="avatar" data-bind="style: 
    { background: s, width: '50px', height: '85px', left: (x() + 'px'), top: 
    (y() + 'px') }">${s}, ${x}, ${y}</div> 

If you use an observable in an expression, then it needs to be specified with (), as it won't get unwrapped automatically.

http://jsfiddle.net/rniemeyer/6GtV3/


This is not a direct answer but I googled onto this page while investigating. I had something like this:

<div data-bind="style: { backgroundImage: src }">

where src is a value in my model object like "http://image.com/foo.jpg". Specifying src as a function as in the above answer did not help:

<div data-bind="style: { backgroundImage: src() }">

I found that if the src value is not a valid background-image property, it is completely ignored.

I had to use:

<div data-bind="style: { backgroundImage: 'url(\'' + src() + '\'' }">

Might save someone some pain at some point :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜