私はjQueryのコールバックと遅延関数で遊んでいて、なぜこれが機能するのか誰かに教えてもらえないかと思っていました
http://jsfiddle.net/austinbv/QVujr/
get_each_total = function(callback) {
var requests;
requests = [];
var url;
url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
return requests.push($.getJSON(url, function(data) {
}));
return $.when.apply($, requests).then(function() {
callback();
}, function() {
return alert("There was an error communicating with a remote library, try again in a few");
});
};
get_each_total_broken = function(callback) {
var requests;
requests = [];
var url;
url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
return requests.push($.getJSON(url, function(data) {
}));
return $.when.apply($, requests).then(function() {
callback();
}, function() {
return alert("There was an error communicating with a remote library, try again in a few");
});
};
$(function () {
get_each_total(alert("success"));
get_each_total_broken(alert("fail"));
});
そしてこれはしません
http://jsfiddle.net/austinbv/wzve6/
get_each_total = function(callback) {
var requests;
requests = [];
var url;
url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
return requests.push($.getJSON(url, function(data) {
}));
return $.when.apply($, requests).then(function() {
callback();
}, function() {
return alert("There was an error communicating with a remote library, try again in a few");
});
};
get_each_total_broken = function(callback) {
var requests;
requests = [];
var url;
url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
return requests.push($.getJSON(url, function(data) {
}));
return $.when.apply($, requests).then(function() {
callback();
}, function() {
return alert("There was an error communicating with a remote library, try again in a few");
});
};
$(function () {
get_each_total(function () { alert("success")});
get_each_total_broken(function () {alert("fail")});
});
ご覧のとおり、唯一の違いは最後の2行にあり、無名関数がコールバックをラップします。どんな洞察もいいでしょう。