【问题标题】:Ember computed properties in CoffeescriptCoffeescript 中的 Ember 计算属性
【发布时间】:2012-09-28 11:18:16
【问题描述】:

我想在 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 中正确实现此视图?

【问题讨论】:

    标签: coffeescript ember.js


    【解决方案1】:

    已经很久了,但我认为应该这样写:

    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'    
    )
    

    【讨论】:

    • 哇,真快!该问题已解决,因此我接受了您的回答,但我认为我的代码不正确,我正在尝试弄清楚如何正确访问content.id,因为现在它是未定义的。无论如何,这里转换为咖啡脚本的主要问题已经解决。谢谢!
    【解决方案2】:
    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')
    

    【讨论】:

    • 你能在coffeescript中做'item-%@'.fmt吗?我记得收到了一个错误
    【解决方案3】:

    我喜欢用Ember.computed

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

    【讨论】:

    • 这看起来比那些奇怪的parens好得多。
    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2017-05-21
    相关资源
    最近更新 更多