Generate methods at runtime in emberJS

51 Views Asked by At

Im trying to generate few methods at runtime in ember and code I'm trying is

App.TestController = Ember.ArrayController.extend App.AnotherMixin,

  unsubmitted: Em.computed.filterBy("model", "unsubmitted", true)
  submitted: Em.computed.filterBy("model", "submitted", true)
  canceled: Em.computed.filterBy("model", "canceled", true)
# Rather than using above methods I'm trying to generate them with meta-programming.

  that: @
  defineAttributes: (->
    [
      "unsubmitted"
      "submitted"
      "cancelled"
    ].forEach ( f ) ->
      Em.defineProperty that , f, Em.computed.filterBy("model", f, true)
      return
    return
  ).on("init")

But its not generating methods. So is there anything Im missing?

1

There are 1 best solutions below

0
On BEST ANSWER

You're defining that as a property on the controller, but trying to use it as a local variable in your defineAttributes method. Change that to a local variable in the method and it should work fine. Or even better yet, just use Coffeescript's fat arrow function to maintain the current value of this:

defineAttributes: (->
    ['unsubmitted', 'submitted', 'cancelled'].forEach (f) =>
        Em.defineProperty this, f, Em.computed.filterBy('model', f, true)
).on('init')