Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js binding a css style in a template

Tags:

ember.js

This is solved since Ember 1.8 with the HTMLBars engine.

I would like to bind a css style in a template. What would be the solution ?

I tried this:

<div class="bar" style="width:{{barWidth}}px"></div>

but DOM element look like this after its been rendered:

<div class="bar" style="width:<script id='metamorph-28-start' type='text/x-placeholder'></script>5.000000000000002<script

id='metamorph-28-end' type='text/x-placeholder'>px">

Obviously here we can see that the tag for metamorph was added within the style attribute...

I'm wondering what is the best way to achieve such things with Ember.js


There is something i don't get yet.

I have a template as follow:

<script type="text/x-handlebars" data-template-name="listTemplate">
<ul id="list">
    {{#each App.list}}
      <li {{bindAttr data-item-id="itemId"}}>
        <div>
            <span class="label">{{itemName}}</span>
            <div class="barContainer">
              <div class="bar" {{bindAttr style="barWidth"}}></div>   
              <div class="barCap"></div>
            </div>
        </div>
      </li>
    {{/each}}
    </ul>

i'm in a for each loop that loops thru my ArrayProxy content... and the bar width vary depending of the value of each item in the list. Your solution here will not work as the view is the UL and i need a barWidth per model item. and I do not want to polute my Model with css related things like "width: ###px"

Is there any other elegant way to solve what i try to do ? maybe it would be radically different. I'm very new to ember.js and try to discover the best-practices yet:)

like image 720
Yaniv De Ridder Avatar asked Jan 27 '12 13:01

Yaniv De Ridder


4 Answers

Set a string on your view that looks like "width: 100px" and then bind it to your div with the bind-attr helper like so: <div {{bind-attr style="divStyle"}}>Test</div>

http://jsfiddle.net/tomwhatmore/rearT/1/

like image 108
Tom Whatmore Avatar answered Nov 01 '22 20:11

Tom Whatmore


To simplify all that, I created a tiny handlebars helper for emberjs that allows you to bind any style properties. You can look at https://github.com/yderidde/bindstyle-ember-helper

like image 22
Yaniv De Ridder Avatar answered Nov 01 '22 20:11

Yaniv De Ridder


Add unbound:

<div class="bar" style="width:{{unbound barWidth}}px"></div>
like image 11
Bogdan M. Avatar answered Nov 01 '22 19:11

Bogdan M.


In Ember 2.0:

<div class="bar" style="width:{{barWidth}}px"></div>

will just work.

like image 1
Daniel Kmak Avatar answered Nov 01 '22 18:11

Daniel Kmak