0
votes

I have an Ember object that has several actions :

MyObject = Ember.Object.extend {
 action1: ->
  console.log "do 1"

 action2: ->
  console.log "do 2"
}

I'd like to call one of these action depending on some condition. The easy way is to check for this condition and call the needed condition using if or switch-case. But, I need something more scalable like a hash of method inside my object and invoke the needed method by just sending their name like object.exec('action1').

Does ember object has already this feature ?

1
Did you try something like: obj.get('action1').apply(obj, yourarguments) ?louiscoquio
I got an error : Funtion.prototype.apply: Arguments list was wrong typejrabary
apply takes two arguments: the value for this, and an array of arguments. If you wants to pass arguments without put them in an array, you should use call which takes the value for this as the first argument, and all others arguments are directly passed to the method. I suggest you to read the first answer: goo.gl/5z6yxlouiscoquio

1 Answers

0
votes

Here's a quick implementation of a dynamic methods' call method in javascript.

var obj = {
 action1 : function(item) {
    return item;
 }, 
 action2 : function(item) { 
    return item;
 }, 

 exec:function(name){
    if(this[name] ==== 'undefined') return;
    var args = Array.prototype.slice.call(arguments);
    return this[name](args.slice(1,args.length))
 }
}

obj.exec('action1','Hello')
obj.exec('action2','World')

Should return Hello World