2013-12-10 13 views
4

如何從操作中返回一些值? 我嘗試這樣做:如何從emberjs中的操作返回值

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

... 

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

您可以指定模板裏面有什麼傳遞 {{行動「DoSomething的」項目}} 和內你會做這樣的行動: someAction:功能(項目){} –

回答

3

行動不返回值,只有真/假/未定義允許冒泡。定義一個函數。

灰燼代碼:

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

+0

提取將值返回給函數並調用該函數的邏輯,如果給出更具體的示例,我可以更具體地示例 – Kingpin2k

1

嘗試的

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

代替

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

區別是排字錯誤,有一個錯字 –

+0

對不起,我糾正了那個帖子。 – redshoghal

0

只需使用@set您要返回

actions:{ 
    someAction: function(){ 
    // return "someValue"; 
    this.set('var', someValue); 
    }  
} 
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

01的第一個參數方法需要與您正在運行的返回函數相同的對象;它設置了this參考的上下文。否則,該函數將從對象中檢索並從當前的this上下文中運行。通過定義像這樣的返回值函數,您可以讓模型做很好的事情。

更新我剛剛發現的API在這個功能似乎做到這一點:http://emberjs.com/api/#method_tryInvoke

+0

在Ember 1.6 0.1。優秀的答案,正是我所期待的。感謝您的發表! – rog