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

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

Asked on November 21, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

       Grouping the strings is work :

    data-bind="style: { backgroundImage: 'url(\'' + image() + '\')' }"
    

       If image is actually an observable,Then call the image or else it  grouping the function instead.

       Note: If binding to an expression involving the property, Then  call the function (with ()). Or else  Javascript expression is  end that concatenates the function itself.
    The main reason to  don’t need () for simple bindings is that Knockout detects when the binding giveback a property function and calls it .

    Answered on November 21, 2018.
    Add Comment

       Use the url() within the   model view :

    var items= [
    {"image": "url(/images/image1.jpg)" },
    {"image": "url(/images/image2.jpg)" },
    {"image": "url(/images/image3.jpg)" }
    ];
    

       Then data-bind the image as usual:

    data-bind="style: { 'background-image': image }"
    
    Answered on November 21, 2018.
    Add Comment

        Use this code to do a knockout binding:

    <div data-bind="foreach: items">
      <div class="box" data-bind="style: {'backgroundImage': 'url('+ image +')'}"></div>
    </div>
    
    Answered on November 21, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.