0
votes

Currently I have a foreach binding with ko with an img tag inside. I want to get this image as a src data string from an authorized web api 2 service.

These images are heavy, so I don't want to load them as src data with the model. I also don't want to directly link to them, because I want the "get" of the image to be an authorized request.

<div class="owl-carousel owl-theme" data-bind="foreach: loadedScreen().Screen_Mockup">
    <img class="owl-carousel-img-util" data-bind="attr: { src: getMockupImageById(screen_mockup_id()) }">
</div>

This kinda works, but only if there is no ajax involved. If my getMockupImageById() method just returns a string, it is correctly populated.

If however I try to make an ajax request and return it from the success callback, it's not. My web service returns strings of this kind: "data:image/png;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4gxYSUNDX1BST0ZJTEUAAQEAAAxITGlu..."

1

1 Answers

1
votes

Knockout is built around the concept of using observable properties to tell it which changes it needs to react to. If you bind the DOM to a normal function nothing will ever tell knockout to update the UI. You should declare the image source as an observable property on your model, and then update that observable when your ajax returns.

This is pseudo-code, but it might look something like:

<div class="owl-carousel owl-theme" data-bind="foreach: loadedScreen().Screen_Mockup">
    <img class="owl-carousel-img-util" data-bind="attr: { src: mySource }">
</div>

...

mySource = ko.observable();

getMockupImageById(screen_mockup_id()).done(function(result){
    mySource(result);
})