Javascript 如何使用jquery proxy()将参数传递给已经有其他参数的函数
根据询问,我已将代码更新到我的特定问题:Javascript 如何使用jquery proxy()将参数传递给已经有其他参数的函数,javascript,jquery,parameter-passing,Javascript,Jquery,Parameter Passing,根据询问,我已将代码更新到我的特定问题: function A(){ this.data1 = null; this.data2 = null; } A.prototype.receiveData1AndData2FromServer = function(callback){ this.doneCallback = $.proxy( function foo(importantData, callback){ this.data1 = important
function A(){
this.data1 = null;
this.data2 = null;
}
A.prototype.receiveData1AndData2FromServer = function(callback){
this.doneCallback = $.proxy( function foo(importantData, callback){
this.data1 = importantData.data1;
this.data2 = importantData.data2;
callback != undefined ? callback() : null;
}, this, callback);
checkFail = $.proxy(
function (jqXHR, textStatus, errorThrown) {
try {
var str = new String(jqXHR.responseText);
var result = JSON.parse(str.substring(str.indexOf('{')));
this.doneCallback(result);
} catch (ex) { console.log(ex); }
}
, this);
$.ajax({
type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
}).done(this.doneCallback)
.fail(checkFail);
}
(问题是回调参数正在替换第一个参数(importantData),而不是第二个。)
对于来自服务器的::ReceiveData1和Data2,存在使用不同回调参数的调用。
我想将回调传递给A::doneCallback,因此当检索完成时,将调用正确的回调。您的问题不是很清楚,但支持多个参数,因为版本1.6经过思考,我找到了解决方案。 将上下文参数拆分为具有多个字段(上下文和所需参数)的对象解决了此问题。我希望它对其他人有用
function A(){
this.data1 = null;
this.data2 = null;
}
A.prototype.receiveData1AndData2FromServer = function(callback){
this.doneCallback = $.proxy( function foo(importantData, callback){
this.context.data1 = importantData.data1;
this.context.data2 = importantData.data2;
this.callback.callback != undefined ? this.callback() : null;
}, {context:this, callback:callback});
checkFail = $.proxy(
function (jqXHR, textStatus, errorThrown) {
try {
var str = new String(jqXHR.responseText);
var result = JSON.parse(str.substring(str.indexOf('{')));
this.doneCallback(result);
} catch (ex) { console.log(ex); }
}
, this);
$.ajax({
type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
}).done(this.doneCallback)
.fail(checkFail);
}
这看起来很可疑,试着准确地解释一下你想做什么,因为肯定还有其他的方法`