Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return values from actions in emberjs

Tags:

ember.js

how to return some value from actions?? I tried this:

var t = this.send("someAction", params);

...

    actions:{
      someAction: function(){
          return "someValue";
      }    
    }
like image 787
redshoghal Avatar asked Dec 10 '13 17:12

redshoghal


2 Answers

actions don't return values, only true/false/undefined to allow bubbling. define a function.

Ember code:

  send: function(actionName) {
    var args = [].slice.call(arguments, 1), target;

    if (this._actions && this._actions[actionName]) {
      if (this._actions[actionName].apply(this, args) === true) {
        // handler returned true, so this action will bubble
      } else {
        return;
      }
    } else if (this.deprecatedSend && this.deprecatedSendHandles && this.deprecatedSendHandles(actionName)) {
      if (this.deprecatedSend.apply(this, [].slice.call(arguments)) === true) {
        // handler return true, so this action will bubble
      } else {
        return;
      }
    }

    if (target = get(this, 'target')) {
      Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function');
      target.send.apply(target, arguments);
    }
  }
like image 70
Kingpin2k Avatar answered Oct 19 '22 11:10

Kingpin2k


I had the same question. My first solution was to have the action put the return value in a certain property, and then get the property value from the calling function.

Now, when I need a return value from an action, I define the function that should be able to return a value seperately, and use it in an action if needed.

App.Controller = Ember.Controller.extend({
    functionToReturnValue: function(param1, param2) {
        // do some calculation
        return value;
    },
});

If you need the value from the same controller:

var value = this.get("functionToReturnValue").call(this, param1, param2);

From another controller:

var controller = this.get("controller"); // from view, [needs] or whatever

var value = controller.get("functionToReturnValue").call(controller, param1, param2); // from other controller

The first argument of the call() method needs to be the same object that you are running the return function of; it sets the context for the this reference. Otherwise the function will be retrieved from the object and ran from the current this context. By defining value-returning functions like so, you can make models do nice stuff.

Update I just found this function in the API that seems to do exactly this: http://emberjs.com/api/#method_tryInvoke

like image 1
Tails Avatar answered Oct 19 '22 11:10

Tails