如何在EmberJS中从动作中返回值

5
如何从actions返回某些值?我尝试了以下代码:
var t = this.send("someAction", params);

...

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

在模板内部,您可以指定要传递的内容{{action 'dosomething' item}},在操作内部,您可以像这样执行某些操作:someAction: function(item){}。 - Michael Guild
5个回答

5

动作不返回值,只返回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
我需要从另一个动作中调用一个动作并使用返回值。 - redshoghal
将返回值的逻辑提取到一个函数中并调用该函数,如果您提供更具体的示例,我可以更具体。 - Kingpin2k

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() 方法的第一个参数需要是运行返回函数的相同对象;它设置了this引用的上下文。否则,该函数将从对象中检索并从当前this上下文运行。通过这样定义具有返回值的函数,您可以使模型做一些好事情。 更新:我刚在API中找到了这个函数,似乎正是这样做的:http://emberjs.com/api/#method_tryInvoke

在Ember 1.6.1中成功使用了这个。非常好的答案,正是我所需要的。谢谢你的发布! - rog

1
看这个例子:
let t = this.actions.someAction.call(this, params);

0

尝试

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

替代

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

差别在于错别字,有一个错别字。 - Roman Pushkin

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接