如何从emberjs中的动作返回值

时间:2013-12-10 17:10:21

标签: ember.js

如何从动作中返回一些值? 我试过这个:

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

...

    actions:{
      someAction: function(){
          return "someValue";
      }    
    }

5 个答案:

答案 0 :(得分:4)

动作不返回值,只返回true / false / undefined以允许冒泡。定义一个函数。

Ember代码:

  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);
    }
  }

答案 1 :(得分:1)

我有同样的问题。我的第一个解决方案是让操作将返回值放在某个属性中,然后从调用函数中获取属性值。

现在,当我需要一个动作的返回值时,我定义了应该能够单独返回一个值的函数,并在需要时在一个动作中使用它。

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

如果您需要来自同一控制器的值:

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

来自另一个控制器:

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

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

call()方法的第一个参数需要与运行return函数的对象相同;它设置this引用的上下文。否则,将从对象中检索该函数,并从当前this上下文中运行。通过定义像这样的值返回函数,你可以让模型做得很好。

更新我刚刚在API中找到了这个功能,似乎就是这样做的:http://emberjs.com/api/#method_tryInvoke

答案 2 :(得分:0)

尝试

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

而不是

vat r = this.send("someAction", params);

答案 3 :(得分:0)

只需使用@set作为您想要返回的设置值

actions:{
  someAction: function(){
    //  return "someValue";
    this.set('var', someValue);
  }    
}

答案 4 :(得分:0)

看这个例子:

let t = this.actions.someAction.call(this, params);
相关问题