I have an observable array with
var items= [ {"image": "/images/image1.jpg" }, {"image": "/images/image2.jpg" }, {"image": "/images/image3.jpg" } ];
My template looks like this:
<div data-bind="foreach: items"> <div class="box" data-bind="style: {'background-image': url(image)}"></div> </div>
Unfortunately, this does not work. What I want is this:
<div> <div class="box" style="background-image: url(/images/image1.jpg)"></div> <div class="box" style="background-image: url(/images/image2.jpg)"></div> <div class="box" style="background-image: url(/images/image3.jpg)"></div> </div>
How can I reach this?
You need to concatenate your strings:
data-bind="style: { backgroundImage: 'url(\'' + image() + '\')' }"
If image
is actually an observable, you'll need to call it, or you'll end up concatenating the function instead.
Note that since you're binding to an expression involving the property, you must call the function (with ()
). Otherwise, you will end up with a Javascript expression that concatenates the function itself.
The only reason you don't need ()
for simple bindings is that Knockout detects when the binding returns a property function and calls it for you.
I don't know if this is any better or worse...
I assembled the url() inside my modelview:
var items= [ {"image": "url(/images/image1.jpg)" }, {"image": "url(/images/image2.jpg)" }, {"image": "url(/images/image3.jpg)" } ];
Then I could data-bind the image as usual:
data-bind="style: { 'background-image': image }"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With