Ember.js - 基于对象属性更新CSS宽度 [英] Ember.js - Update CSS width based on an object property

查看:144
本文介绍了Ember.js - 基于对象属性更新CSS宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@ andorov的回答所述,OP的理想代码(< div style = width:{{model.width}}> 现在几乎就像Ember 1.10一样。

As mentioned in @andorov's answer, the OP's ideal code (<div style="width:{{model.width}}"> now pretty much just works as of Ember 1.10


我是Ember.js的新人,我发现很难动态
改变CSS。这里是一个例子来解释我的意思:

I am new to Ember.js, and I am finding it difficult to dynamically change CSS. Here is an example to explain what I mean:

var App = Em.Application.create();

App.MyObj=Em.Object.extend({
    objWidth:10
});

App.objController = Ember.ArrayController.create({
    content: [],
  createObj: function(){
      var obj = App.MyObj.create();
      this.pushObject(obj);
  }
});

下面的代码不工作,但它解释了我的目标。使用
Handlebars模板,我想要完成这个:

The code below doesn't work, but it explains my goal. Using a Handlebars template, I want to accomplish this:

{{#each obj in App.objController}}
     <div style="width:{{obj.objWidth}}"></div>
{{/each}}

换句话说,当 objWidth 属性更改时< div> 更新

In other words, I just want to have the width of the <div> update when the objWidth property is changed.


推荐答案

style 属性必须与 bindAttr ,传递样式作为一个整体,而不只是一个属性,因为它不明白。此属性仅允许您以字符串形式访问样式,以定位即时元素。

The style property has to be bound with bindAttr, passing the style as a whole, not just one of the properties, as it doesn't understand that. This property only gives you access to the style as a string, targeting the immediate element. It's not possible to bind to a property of the style if you define it like that.

因此,这里是我的sugestion :我创建了几个模型类像下面,实现一个属性返回宽度的像素:

So here's my sugestion: I've created a couple of "model" classes like the following, implementing a property that returns the width in pixels:

var WidthEnabledModel = Em.Object.extend({
    width: 100,
    unit: "px",
    widthString: function() {
        return 'width: %@%@'.fmt(this.width, this.unit);
    }.property('width', 'unit')            
});

App.SampleModel = WidthEnabledModel.extend({
    itemName: ''
});

然后,对于集合中的每个项目,我将该属性绑定到 style 属性:

Then, for each item in your collection I'm binding that property to the style attribute:

<script type="text/x-handlebars" data-template-name="sample">
    <div id="sample_area" style="width: 250px;">
    {{#each thing in controller.content}}
      <div class="item" {{bindAttr style="thing.widthString"}}>
          {{thing.itemName}}<br />
          {{thing.widthString}}
      </div>
    {{/each}}
    <div>
</script>

按照我在jsfiddle这里做的完整代码示例http://jsfiddle.net/schawaska/ftWZ6/

Follow the example with full code I've made at jsfiddle here http://jsfiddle.net/schawaska/ftWZ6/

编辑:
我在小提琴上做了一些更改以添加更多的功能,但是设置宽度的部分保持不变。

I've made some changes in the fiddle to add more feature, but the part to set the width stays the same.

这篇关于Ember.js - 基于对象属性更新CSS宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆