How can I do a knockout binding to a backgroundImage URL?

binding, css, knockout.js

Solution

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.

Problem

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?

Original source