简体   繁体   English

使用剔除法,如何将图像src绑定到异步方法?

[英]With knockout, how to bind an image src to an asyncronous method?

Currently I have a foreach binding with ko with an img tag inside. 目前,我有一个带有ko的foreach绑定,其中带有img标签。 I want to get this image as a src data string from an authorized web api 2 service. 我想从授权的Web api 2服务获取此图像作为src数据字符串。

These images are heavy, so I don't want to load them as src data with the model. 这些图像很重,所以我不想将它们作为src数据加载到模型中。 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. 这种方法有效,但前提是不涉及Ajax。 If my getMockupImageById() method just returns a string, it is correctly populated. 如果我的getMockupImageById()方法仅返回一个字符串,则说明它已正确填充。

If however I try to make an ajax request and return it from the success callback, it's not. 但是,如果我尝试发出ajax请求并从成功回调中返回它,则不是。 My web service returns strings of this kind: "data:image/png;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4gxYSUNDX1BST0ZJTEUAAQEAAAxITGlu..." 我的Web服务返回以下字符串:“ data:image / png; base64,/ 9j / 4AAQSkZJRgABAQEASABIAAD / 4gxYSUNDX1BST0ZJTEUAAQEAAAxITGlu ...”

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. 如果将DOM绑定到普通函数,则不会告诉淘汰者更新UI。 You should declare the image source as an observable property on your model, and then update that observable when your ajax returns. 您应该在模型上将图像源声明为可观察的属性,然后在ajax返回时更新该可观察的属性。

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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM