Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 562
user1482949 Avatar asked Jun 26 '12 14:06

user1482949


2 Answers

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.

like image 159
SLaks Avatar answered Oct 15 '22 00:10

SLaks


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 }" 
like image 36
fitzgeraldsteele Avatar answered Oct 15 '22 01:10

fitzgeraldsteele