wintermeyer
wintermeyer

Reputation: 8318

Add a function which returns a search and replace for an attribute

app/models/pictures.js

import DS from 'ember-data';

var Picture = DS.Model.extend({
  url: DS.attr('string')
});

export default Picture;

This is an example JSON data set:

{
 - pictures: [
    - {
        id: 1,
        url: "http://example.com/path/large/example.jpg"
      }
   ]
}

I need to display a smaller version of a picture which is already stored on the server but has medium instead of large in the URL. How can I add a function to the picture model which returns a search and replace for s/large/medium/ of the url attribute?

Upvotes: 0

Views: 49

Answers (1)

Daniel
Daniel

Reputation: 18680

You need to use computed property which depends upon url property and returns its modified version:

var Picture = DS.Model.extend({
    url: DS.attr('string'),
    urlReplaced: Ember.computed('url', function() {
      var url = this.get('url');
      if (url) {
        return url.replace('large', 'medium');
      }
    })
});

Then you can use:

<img src={{model.urlReplaced}} />

Where model is concrete instance of Picture model.

Upvotes: 1

Related Questions