Referencing static files with composite URLs in SproutCore

406 Views Asked by At

I’m using static_url to refer to static files that are located in the resources directory. This works fine when for literal URL strings but it doesn’t work for composite URLs that were constructed using variables:

static_url(foo + '/' + bar)

This is just ignored by SproutCore’s pre-processor.

So is there some way to refer to a static file with a composite URL? Or, since I’m working with a finite set of URLs, do I have to introduce each composite URL before I can refer to it?

1

There are 1 best solutions below

1
On

This answers assumes that you are using SC1.

I believe that static_url() is processed by the build tools (sc-build and sc-server) at compile time and not the framework at runtime.

The code for the build tools can be found at https://github.com/sproutcore/abbot. I believe base.rb replace_static_url() is where the work gets done.

So the following code:

imageView: SC.ImageView.design({
  layout: { top: 0, left: 0, width: 200, height: 18 },
  value: static_url('picture.png')
})    

gets compiled into the following before being delivered to the browser:

imageView: SC.ImageView.design({
  layout: { top: 0, left: 0, width: 200, height: 18 },
  value: '/static/vvv/en/current/source/resources/picture.png?1320555999'
})  

To create composite URL at runtime, try using bindings.

// In your view
imageView: SC.ImageView.design({
  layout: { top: 0, left: 0, width: 200, height: 18 },
  valueBinding: 'Vvv.controller.imageValue'
}) 

// In another file, define the controller
Vvv.controller = SC.Object.create({
    foo: '/static/vvv/en/current/source/resources',
    bar: 'bug.png',

    imageValue: function() {
       return this.get('foo') + '/' + this.get('bar');
    }.property().cacheable()
});

Also, if you have a finite set of resources, you may want to give this a go:

Vvv.controller = SC.Object.create({
    foo: static_url('foo.png'),
    bar: static_url('bar.png'),
    isFoo: false,

    imageValue: function() {
       if (this.get('isFoo')) {
           return this.get('foo');
       } else {
           return this.get('bar');
       }
    }.property('isFoo').cacheable()
});

You can change the image at runtime by setting isFoo to true or false.

Hope this helps.