回调函数中的参数是怎么处理的?

51 views
Skip to first unread message

ayanamist

unread,
Aug 16, 2012, 9:16:54 AM8/16/12
to win...@googlegroups.com
在看Wind.js的sample,看到
https://github.com/JeffreyZhao/wind/blob/master/samples/async/browser/weibo.html#L50
这句,其中的result.data是对应原来的回调函数的data,那如果原来的回调函数为function(arg1, arg2, arg3...)这样有多个参数的呢?那result代表的是什么?
更进一步,如果原来的回调函数是function(){for(var i=0;i<arguments.length;i++){//blahblah}}这样通过arguments来读取数据的呢?Wind.js该如何处理?

Jeffrey Zhao

unread,
Aug 24, 2012, 12:14:31 PM8/24/12
to win...@googlegroups.com
����Կ�һ����ƪ�ĵ�

http://windjs.org/cn/docs/async/helpers.html

����

-----Original Message-----
From: ayanamist
Sent: Thursday, August 16, 2012 9:16 PM
To: win...@googlegroups.com
Subject: [windjs] �ص������еIJ�������ô����ģ�

�ڿ�Wind.js��sample������
https://github.com/JeffreyZhao/wind/blob/master/samples/async/browser/weibo.html#L50
��䣬���е�result.data�Ƕ�Ӧԭ���Ļص������data�������ԭ���Ļص�����Ϊfunction(arg1,
arg2, arg3...)�����ж��������أ���result������ʲô��
���һ�������ԭ���Ļص�������function(){for(var
i=0;i<arguments.length;i++){//blahblah}}����ͨ��arguments����ȡ��ݵ��أ�Wind.js����δ��?

--



Rainbow_sh

unread,
Sep 21, 2012, 11:58:52 AM9/21/12
to win...@googlegroups.com, ayan...@gmail.com
这个是这样的,例子在定义Task的时候,将Option中的Success和Error重新定义了。如果寻这个思路,去处理,那么对于用户定义的回调函数将不会处理,原因是在定义Task时重新定义的事件覆盖了原来用户定义的事件。
处理也比较简单,就是在重新定义的回调函数中,调用用户的回调函数即可。
例如,示例中(jquery-binding.js):
$.ajaxAsync = function (options) {
        return Task.create(function (t) {

            options.success = function (data, textStatus, jqXHR) {
                t.complete("success", {
                    data: data,
                    textStatus: textStatus,
                    jqXHR: jqXHR
                });
            }

            options.error = function (jqXHR, textStatus, errorThrow) {
                t.complete("failure", {
                    jqXHR: jqXHR,
                    textStatus: textStatus,
                    errorThrow: errorThrow
                });
            };

            $.ajax(options);
        });
    };

那么如果用户定义了success事件或者error事件怎么处理呢?
$.ajaxAsync = function (options) {
        return Task.create(function (t) {
            var successFunc=options.success;
            options.success = function (data, textStatus, jqXHR) {
               if(successFunc) successFunc(data, textStatus, jqXHR);
                t.complete("success");
            }

            options.error = function (jqXHR, textStatus, errorThrow) {
                t.complete("failure", {
                    jqXHR: jqXHR,
                    textStatus: textStatus,
                    errorThrow: errorThrow
                });
            };

            $.ajax(options);
        });
    };

这里需要注意的是要定义一个中间变量来传递对用户定义的事件的引用,否则会造成循环引用;另外需要注意调用的位置应该是在t.complete('success')之前。
Reply all
Reply to author
Forward
0 new messages