In an Ember.js Handlebars template, is there a way to have both static and dynamic class attributes?

StackOverflow https://stackoverflow.com/questions/8807783

  •  26-10-2019
  •  | 
  •  

Question

Using the already-overused to-do app example, let's say I want an element with a "todo" class (static) and an "is-done" class (dynamic):

<div {{bindAttr class="todo isDone"}}>
  Other stuff in here
</div>

In this case, "isDone" and "todo" are both expected to be properties on my view object, which is what I want for "isDone", but not for "todo". I'm currently working around this by adding a "todo" property on my view that is equal to a static "todo" string. Is there any way to have a static class attribute when using bindAttr?

Fiddle example: http://jsfiddle.net/nes4H/4/

Was it helpful?

Solution

EDIT:

We've fixed this in Ember!

On a build from master, or after 0.9.6 is released, you can now do:

<div {{bindAttr class="App.foo:a-bound-class :a-static-class"}}></div>


Previous answer:

You unfortunately can't have both static and dynamic class names when using bindAttr.

I suggest using one or more computed properties on your view to output both static and dynamic class names.

Supporting both static and dynamic class names would be very nice, but the way bindAttr currently works, it's not possible. bindAttr doesn't know anything about the element it's being attached to during template compilation.

OTHER TIPS

I don't know if you can do it with bindAttr, but the #view helper does allow you to set both static classes and dynamic ones:

{{#view App.TodoView class="todo" classBinding="isDone"}}
  inner content
{{/view}} 

In Ember master, a change was committed today to allow static classes to be specified within bindAttr by prepending a colon.

https://github.com/emberjs/ember.js/commit/ce385e3294be019215c555511c7f393aebc02e41

This may change before the next release, of course, but this is a problem that the Ember core team wants to solve.

In ember 1.10.0, bindAttr is deprecated. You can directly bound a variable to class of div. here the color variable is bound to the class of a div:

<div class="{{color}}"></div>

The inline if helper can also be used in these contexts:

<div class="{{color}} {{if isEnabled 'active' 'disabled'}}"></div>

http://emberjs.com/blog/2015/02/07/ember-1-10-0-released.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top