4

I want to set the style of a link-to helper but don't quite understand how.

I have the following model:

App.ArtistFavorite = DS.Model.extend
  name: DS.attr 'string'
  image_url: DS.attr 'string'

My template:

li
  link-to 'artistFavorite' this {bind-attr style="background-image: url('image-url');"}

But the bind-attr doesn't seem to work

BTW: I'm using emblemjs and coffeescript

Mexxer
  • 1,699
  • 5
  • 27
  • 40

1 Answers1

3

link-to is an Ember view helper, so (inspired by this) I was originally going to suggest using attributeBindings, except that raises the following JS error:

Setting 'attributeBindings' via Handlebars is not allowed. Please subclass Ember.View and set it there instead.

It looks like if you really need to set attributes in this way, it is possible to do so by reopening the Ember.LinkView class and setting attributeBindings there, but be forewarned that this will affect every link-to on your page.

But if (as it appears) the only attribute you need to set is style, you can just create a CSS class with your desired style and then set classNames, as discussed here, i.e.:

{{#link-to 'artistFavorite' this classNames="your-class-name"}}

From a code-style perspective, I would go with this approach even if it was possible to (more easily) set the style attribute directly.


Edit: Just realized you are trying to individually set styles for each link using one of the attributes of the corresponding item, so obviously CSS classes would not work. I've thought about this a bit more though.

Although discouraged, you should be able to bind to the style attribute by reopening the LinkView class and adding style to the attributeBindings:

Ember.LinkView.reopen({
  attributeBindings: ["style"]
})

Then possibly you could set a value for the style attribute:

{{#link-to 'artistFavorite' this style=favStyle}}

Where favStyle is a computed property on your model or (ideally) your controller:

favStyle: function() {
  return "background-image: url('" + this.get('image_url') + "');";
}.property('image_url')

However I haven't tested this and I'm not 100% certain the binding will work correctly this way, because these bindings are typically used for plain-text, not properties.

Community
  • 1
  • 1
gorner
  • 552
  • 2
  • 8