如何向Ember.js对象添加动态方法名称?

时间:2012-11-01 21:11:53

标签: javascript coffeescript ember.js

所以基本上我有很多非常相似的函数,只是函数名略有不同,并且访问的变量略有不同。

我不想重复自己,而是想通过类似于Ruby中的define_method创建这些方法。

任何人都知道如何在Ember.js对象中执行此操作?哦,最好是CoffeeScript!

这显然是错误的,但只是一个非常基本的例子。

Thing = Ember.Object.extend()

animal = "cow"
say = "moo"

animal = "dog"
say = "woof"

Thing.reopenClass(
this["#{animal}Speak"]: ->
console.log say
)

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

reopenClass只需要一个对象,这样您就可以构建对象,然后将其交给reopenClass

add_this = { }
add_this["#{animal}Speak"] = -> console.log say
Thing.reopenClass add_this

不幸的是,在为对象文字构建键时不能使用字符串插值,所以显而易见(但不正确):

Thing.reopenClass(
    "#{animal}Speak": -> console.log say
)

给你一个语法错误。

我认为问题的根源是带插值的字符串不是字符串文字,它是一个值为字符串的表达式。对象文字中的键必须是简单的不带引号的标签(label:)或字符串文字('string':"string":)。当你这样说:

"string with #{interpolation}"

你真的只是用这个简写:

"string with " + interpolation

并且CoffeeScript编译器不够智能,无法重写:

o = { "string with #{interpolation}": value }

就像这个JavaScript:

o = { }
o['string with ' + interpolation] = value

因此,您不能将字符串值表达式用作CoffeeScript(或JavaScript)中对象文字的键。