有没有办法通过使用emberjs属性的自动绑定来设置css属性?
就像是:
<div {{bindAttr style="background-color: divColor;"}}>
...
</div>
Run Code Online (Sandbox Code Playgroud)
另一种简单的方法是向模型添加计算属性.
型号----
App.Photo = Em.Object.extend(
objectId: null
url: ""
style: (->
"background-image:url('" + @get("url") + "')"
).property("url")
)
Run Code Online (Sandbox Code Playgroud)
模板-----
{{#each item in App.photoController}}
<div {{bindAttr style="item.style"}}></div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
我得到了这个工作,似乎是最简单的方法.
请注意,截至ember 1.13.bind-attr不推荐使用绑定属性().您需要使用与此类似的代码绑定到类:
<div class={{myClass}}></div>
Run Code Online (Sandbox Code Playgroud)
此外,style不建议以这种方式绑定,因为它可能会引入XSS漏洞.HTML模板会在使用时自动转义HTML以防止XSS {{...}},但样式属性在内置转义范围之外还有其他漏洞.
建议的方法是自己转义CSS(即创建escapeCSS将适当地转义特定CSS 的函数以防止XSS - 这不是内置函数.您可以Ember.Handlebars.Utils.escapeExpression从该基础开始并添加任何其他检查.)更多信息可以在这里找到:https:
//guides.emberjs.com/v2.2.0/templates/writing-helpers/#toc_escaping-html-content
然后你通过使用告诉Ember字符串是"安全的" Ember.String.htmlSafe,Ember不会试图逃避该内容.
控制器:
myStyle: Ember.computed('color', function() {
var color = escapeCSS(this.get('color'));
return new Ember.String.htmlSafe("color: " + color);
})
Run Code Online (Sandbox Code Playgroud)
模板:
<div style={{myStyle}}></div>
Run Code Online (Sandbox Code Playgroud)
参考:http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes
不是那样但是很接近.你必须style自己构建字符串.看看这个jsFiddle.
App = Ember.Application.create();
/**************************
* Models
**************************/
/**************************
* Views
**************************/
App.View = Ember.View.extend({
style: function() {
return "background-color:" + this.get('color');
}.property('color').cacheable()
});
/**************************
* Controllers
**************************/
App.set('controller', Ember.Object.create({
color: "transparent",
red: function() {
this.set('color', 'red');
},
blue: function() {
this.set('color', 'blue');
},
style: function() {
return "background-color:" + this.get('color');
}.property('color').cacheable()
}));
/**************************
* App Logic
**************************/
$(function() {
Run Code Online (Sandbox Code Playgroud)
模板:
{{#view Ember.Button target="App.controller" action="blue"}}BLUE{{/view}}
{{#view Ember.Button target="App.controller" action="red"}}RED{{/view}}
{{#view App.View colorBinding="App.controller.color" attributeBindings="style"}}
Color is {{App.controller.color}}
{{/view}}
<hr>
<div {{bindAttr style="App.controller.style"}}>And another way...</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15864 次 |
| 最近记录: |