Ember计算Coffeescript中的属性

时间:2012-10-08 08:20:13

标签: coffeescript ember.js

我想在Coffeescript中实现以下Javascript代码

App.ItemView = Ember.View.extend({
    classNameBindings: ['itemId'],
    itemId: function() {
        console.log(this.get('content'));
        return "item-%@".fmt(this.get('content.id'));
    }.property('content.id'),
    templateName: 'item'    
}); 

以下是我目前在coffeescript中的内容:

App.ItemView = Ember.View.extend(
    classNameBindings: ['itemId']

    itemId: ->
        console.log this.get('content')
        contentId = this.get('content.id')
        "item-#{contentId}");
    .property('content.id')

    templateName: 'item'    
)

我明白了:

Error: Parse error on line 11: Unexpected '.'

问题似乎与.property('content.id') 中的点有关。我不知道这是如何转化为Coffeescript的。如何在Coffeescript中正确实现此视图?

3 个答案:

答案 0 :(得分:42)

这已经很长一段时间了,但我认为这应该是这样写的:

App.ItemView = Ember.View.extend(
  classNameBindings: ['itemId']

  itemId: (->
    console.log this.get('content')
    contentId = this.get('content.id')
    "item-#{contentId}");
  ).property('content.id')

  templateName: 'item'    
)

答案 1 :(得分:4)

itemId: (->
  content = @get 'content'
  if content
    return 'item-%@'.fmt(content.get 'id')
  null
).property('content.id')

您必须保护计算属性不受可能尚未定义的值的影响。也就是说,如果内容对象上已有id属性,则代码很好。如果内容未定义,那么您将无法查找其ID属性,并且您可能会看到投诉。

您也可以使用

itemId: Ember.computed(->
  ..
).property('content.id')

和观察者的类似模式。实际上,观察者也可以在没有条件的情况下完成同样的事情:

itemId: null

contentIdChanged: (->
  @set 'itemId', 'item-%@'.fmt(@get 'content.id')
).observes('content.id')

答案 2 :(得分:2)

我喜欢使用Ember.computed

itemId: Ember.computed 'firstName', 'lastName', ->
  "#{@get('firstName')} #{@get('lastName')}"
相关问题