[英]Using jquery.when in an object literal
我有一個名為addLocation的javascript / jQuery函數,它是對象文字的一種方法:
addLocation: function(latLng, address=false, elevation=false, pan=false)
{
$.when(geographic.getAddress(latLng), geographic.getElevation(latLng), geographic.getMagneticDeclination(latLng))
.done(function(data){
if (data.status != 'OK') {
window.alert(data.message);
}
if (pan) {
flyityourself.map.panTo(latLng);
flyityourself.map.setZoom(16);
}
flyityourself.addWaypoint(latLng, data);
flyityourself.addMarker(latLng, data);
})
.fail(function(msg) {
window.alert(msg);
}
);
},
這三個函數getAddress,getElevation和getMagneticDeclination都是名為“ geographic”的第二個對象文字的方法。
但是代碼失敗了。
在調試器中,我檢查了所有四個功能。
以前,只有三個方法getAddress,getElevation和getMagneticDeclination位於對象文字“地理”中。 addLocation在一個純.js文件中。 在這種情況下,代碼有效。
但是由於更改了我的代碼以將addLocation放在對象文字中,所以代碼開始失敗。
$ .when在對象字面量上的用法是否有所不同,還是我忘了限定某些內容?
問候。 克里斯·B
答:Wolff在他們發表的評論中是正確的-您需要在完成的回調中添加3個參數,每個參數由when處理一次。
這是一個簡單的示例,提供一個模擬地理對象以使您的代碼在獨立的小提琴中工作:
https://jsfiddle.net/tmLrn4gc/1/
// Mock geographic object for testing
geographic = {
// Return a promise, and a second later, resolve that promise with some
// dummy data.
getAddress: function() {
var dfd = $.Deferred();
window.setTimeout(function() {
dfd.resolve("address:lat1,lng1")
}, 1000);
return dfd.promise();
},
getElevation: function() {
var dfd = $.Deferred();
window.setTimeout(function() {
dfd.resolve("elevation:meters")
}, 1000);
return dfd.promise();
},
getMagneticDeclination: function() {
var dfd = $.Deferred();
window.setTimeout(function() {
dfd.resolve("declination:degrees")
}, 1000);
return dfd.promise();
}
};
// A simplified location manager, showing the 3 promises and a done method.
// The console output in the fiddle shows the 3 promises are resolved as
// desired.
LocationManager = {
addLocation: function(latLng, address=false, elevation=false, pan=false) {
$.when(
geographic.getAddress(latLng),
geographic.getElevation(latLng),
geographic.getMagneticDeclination(latLng)
).done(function(d1, d2, d3) {
console.log("Done", d1, d2, d3);
})
}
}
// Make it all happen!
LocationManager.addLocation();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.