So basically I have many functions that are very similar but just with slightly different function names and accessing slightly different variables.
Instead of repeating myself I want to create these methods via something similar to define_method in Ruby.
Anyone know how to do this in an Ember.js object? Oh and preferably CoffeeScript!
This is obviously wrong but just a very basic example.
Thing = Ember.Object.extend()
animal = "cow"
say = "moo"
animal = "dog"
say = "woof"
Thing.reopenClass(
this["#{animal}Speak"]: ->
console.log say
)
Can anyone help with this?
reopenClassjust needs an object so you can build the object and then hand it toreopenClass:Unfortunately you can’t use string interpolation when building a key for an object literal so the obvious (but incorrect):
gives you a syntax error.
I think the root of the problem is that a string with interpolation is not a string literal, it is an expression whose value is a string. The keys in an object literal must be simple unquoted labels (
label:) or string literals ('string':or"string":). When you say this:you’re really just using a shorthand for this:
and the CoffeeScript compiler isn’t smart enough to rewrite this:
as this JavaScript:
So you can’t use string valued expressions as keys for object literals in CoffeeScript (or JavaScript).