How do I rerender this img element?

佐手、 提交于 2019-12-11 11:48:35

问题


I'm sending the API a remote image url. The API does some image processing, then uploads to AWS S3. If successful, it returns the url to the image in response.data.attributes['image-url']

My controller has:

imageUrl: Ember.computed.oneWay('model.imageUrl');

actions: {
  uploadImage(imageUrl) {
    Ember.$.ajax({
      url: `api/v1/users/1/update-image`,
      type: 'PUT',
      data: {
        data: {
          attributes: {
            'image-url': imageUrl
          }
        }
      }
    })
    .success(response => {
      this.set('imageUrl', response.data.attributes['image-url']);
    })
    .error(response => {
      console.log(response);
    });
  }
}

My template has:

<img src={{imageUrl}}>

API always returns something like https://project1.imgix.net/products/1/image.jpg. Even if image.jpg is an entirely new image.

Ember does not rerender the img element. I have to manually refresh to see the new image on the browser.

Is there any way I can tell Ember that the img element contains a new image and that it should re-render it?

Is there a different approach I should consider instead?

EDIT

So I tried setting imageUrl to null first, then wait a few seconds to set the actual image url. Seems to work, but is this the right way to tackle this situation:

.success(response => {
  this.set('imageUrl', null);

  Ember.run.later((() => {
    this.set('imageUrl', response.data.attributes['image-url'] + '?t=' + (new Date()).getTime());
  }), 3000);
})

I wonder if this has anything to do with running this.set at some specific Ember run loop.


回答1:


To manually let ember know a property has changed, use the notifyPropertyChange. This should make ember recompute and bindings or computed propwerties based on your property. You can use it as this.notifyPropertyChange('imageURL');




回答2:


It looks like oneWay will prevent you from setting that value.

Where computed.alias aliases get and set, and allows for bidirectional data flow, computed.oneWay only provides an aliased get. The set will not mutate the upstream property, rather causes the current property to become the value set. This causes the downstream property to permanently diverge from the upstream property.

Docs

Try changing:

this.set('imageUrl', response.data.attributes['image-url']);

to

this.set('model.imageUrl', response.data.attributes['image-url']);


来源:https://stackoverflow.com/questions/35255715/how-do-i-rerender-this-img-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!