Search code examples
ember.jsember-dataember-cli

EmberJS: Where to place a function for computed properties?


For some of my models I’d like to use the same computed property. But instead of writing the same function in every single model like this:

imageURL: function(){
  var path = '/images/',
      ext = ".jpg";
  return path + this.get('shortID') + ext;
}.property('shortID')

I would like to to something like this

imageURL: function(){
  return makeImageURL(this.get('shortID'));
}.property('shortID')

And have this makeImageURL function somewhere:

makeImageURL = function(shortID) {
  var path = '/images/',
    ext = ".jpg";
  return path + shortID + ext;
}

But where? BTW I am using Ember-CLI.


Solution

  • Have you given any thought to making imageURL a computed property inside a component? This way you can reuse the component whenever you need to.

    Another option would be to create an ember handlebars helper that computes imageURL based on a parameter that is passed to it. See here