在Coffeescript中调用函数定义的方法

10

你如何将这段JavaScript代码转换为CoffeeScript?具体来说,我在如何在函数定义上调用.property()方面遇到了困难。

MyApp.president = SC.Object.create({
  firstName: "Barack",
  lastName: "Obama",

  fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');

    // Call this flag to mark the function as a property
  }.property('firstName', 'lastName')
});

1
良好的实践是声明您的属性依赖项。在您的情况下,您可以执行 property('firstName', 'lastName')。如果您已声明了依赖关系,则还可以使用 .cacheable() 将属性设置为可缓存。 - Peter Wagenet
1
@Peter Wagenet - 很好的观点,我更新了代码以供未来搜索者使用。 - Josh Rickard
4个回答

21

我认为这是你应该写的方式:

MyApp.president = SC.Object.create {
  firstName: "Barack",
  lastName: "Obama",
  fullName: (-> 
    return @get 'firstName' + ' ' + @get 'lastName'
    # Call this flag to mark the function as a property
  ).property('firstName', 'lastName')
}

点击此链接查看


1
您的属性应该依赖于底层属性的更改,以便将计算属性绑定到任何更改。否则,当名字或姓氏更改时,全名将不再反映现实。 - Mike Aski
这是生成的JS代码:App.president = Ember.Object.create({ name: "Barack Obama", firstName: "Barack", lastName: "Obama", fullName: (function() { return "" + (this.get('firstName')) + " " + (this.get('lastName')); }).property('firstName', 'lastName') });当我在控制台运行它时,会收到以下信息:“TypeError:App.president.fullName不是一个函数 在0处调用App.president.fullName()`” - bonyiii
@bonyiii 你不应该将它作为一个函数运行,而应该使用 get('fullName') - Peter Wagenet

5

定义计算属性有几种方法。以下是每种方法的示例:

MyApp.president = Ember.Object.create
  firstName: "Barack"
  lastName: "Obama"
  fullName: (-> 
    @get 'firstName' + ' ' + @get 'lastName'
  ).property('firstName', 'lastName')

MyApp.president = Ember.Object.create
  firstName: "Barack"
  lastName: "Obama"
  fullName: Ember.computed(-> 
    @get 'firstName' + ' ' + @get 'lastName'
  ).property('firstName', 'lastName')

最后的 .property() 调用是多余的。 - Blacktiger
我添加了依赖键。当它们被指定时,它们不是冗余的。 - ebryn

2
使用Ember.computed时,您不需要调用.property(),因此您也可以使用以下形式:
MyApp.president = Ember.Object.create
  firstName: "Barack"
  lastName: "Obama"
  fullName: Ember.computed -> @get 'firstName' + ' ' + @get 'lastName'

0

这样做可以吗?

 (() => this.get("firstName") * this.get("lastName")).property()

没有必要使用“fat-arrow”绑定到this。实际上,这会有害,因为它将绑定到声明作用域,而不是对象本身。 - James A. Rosen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接