user1482949
user1482949

Reputation: 313

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?

Upvotes: 31

Views: 19659

Answers (3)

Dima Dulin
Dima Dulin

Reputation: 21

this is my example. Always use it

<div data-bind="foreach: items">
    <div class="box" data-bind="style: {'backgroundImage': 'url('+ image +')'}"></div>
</div>

Upvotes: 2

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 68

fitzgeraldsteele
fitzgeraldsteele

Reputation: 4557

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 }"

Upvotes: 6

Related Questions