プロトタイプ関数内から呼び出される getJSONP 関数があります。JSONオブジェクトをその関数に渡し、その中の値を変更しています。準備ができたら更新されたオブジェクトを使用できるようにしたいのですが、オブジェクトを返すことができないようです。コールバックから別の関数を呼び出して使用するだけですそこの。
約束の概念を理解していると思いますが、関数を約束に変更して、準備ができたらそれを使用するにはどうすればよいですか?
これは getJSONP 関数です。
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
url += '?callback=' + ud;
script.src = url;
head.appendChild(script);
};
そして、これが私がそれを使用する方法です:
MyClass.prototype.mySpecialFunction = function(myObject) {
getJSONP(myURL,function(data) {
//doing alot of stuff
...
//myObject.myArr = code the pushes a lot of stuff into an array
workWithTheNewArray(myObject) // where i work with the full array
});
});
私はjQueryを使用していないことを考慮してください(パフォーマンスとサイズのため)が、jqliteを使用しています。