![](/img/trans.png)
[英]how to call the same function from two different places in angularjs
[英]How to call a function when its arguments come from different places
我想調用一個函數(showResult),但是每個必需的參數都來自不同的地方。 我必須等到事件處理程序(服務器發送響應)確定價格后,才知道如何傳遞其他必需的參數(產品)。
編輯:澄清一下,server.onResponse是指websocket連接的“ onmessage”事件處理程序( 參考 )
function requestPhoneCost () {
var product = "iPhone 7";
server.requestPrice(product);
}
server.onResponse(function(response) {
//response contains only information about the price, but not
//what product its for
showResult( , response.price);
});
function showResult (product, cost) {
alert(product + " costs " + response + "dollars");
}
在requestPhoneCost
函數中聲明響應函數,以便它可以訪問閉包中的product
。
function requestPhoneCost() {
var product = "iPhone 7";
server.requestPrice(product);
server.onResponse(function(response) {
showResult(product, response.price);
});
}
function showResult(product, cost) {
alert(product + " costs " + response + "dollars");
}
假定server.onResponse()
替換了響應事件偵聽器,而不是添加了其他偵聽器。
這里的根本問題是server
。 它顯然是共享資源,但只有一個帶有響應的回調。 該設計將無法正常工作。
而是讓服務器接受帶有請求的特定呼叫的回調。 然后做您要尋找的是簡單的:
function requestPhoneCost () {
var product = "iPhone 7";
server.requestPrice(product, cost => showResult(product, cost));
}
在當今世界,我將使用promise而不是手動編碼的回調:
function requestPhoneCost () {
var product = "iPhone 7";
server.requestPrice(product)
.then(cost => showResult(product, cost))
.catch(error => { /* handle/report error */);
}
在這兩種情況下,都需要更改server
以便跟蹤與哪些請求相關的回調。 這聽起來比實際要困難得多(實際上確實很容易),但是我們無法為您提供看不到的代碼(例如server
的代碼)。
您已經說過,您在websocket連接的構造函數中設置了中央onResponse
。 IIRC,websocket上的每條消息都有唯一的ID(如果沒有,則可以添加一個ID)。 然后,您可以將有關為請求返回的承諾的信息存儲在以該ID為鍵的Map
:
this.id = 0; // If you need to assign your own IDs
this.settlersById = new Map();
這是服務器類中的概念性requestPrice
方法:
requestPrice(product) {
const id = ++this.id;
const promise = new Promise((resolve, reject) => {
sendRequest({id, product});
this.settlersById.set(id, {resolve, reject});
});
}
然后在onResponse
onResponse(response) {
const {id} = response;
const settlers = this.settlersById.get(id;
if (settlers) {
this.settlersById.delete(id);
if (/* response is a success */) {
resolve(response.data);
} else {
reject(/*...appropriate error...*/);
}
}
}
同樣,這都是概念性的,因為我們沒有您的服務器類。 它使用自己的ID,而websocket可能會為您提供一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.