簡體   English   中英

在原型中定義處理函數

[英]Defining Handler Functions in a Prototye

我正在嘗試創建一個JavaScript原型,該原型將允許我以類似於jQuery ajax調用工作的方式處理流程的結果。 例如:

var request = $.ajax({
    //params here
})
.done(function(data, textStatus, jqXHR) {
    //action here
})
.fail(function (jqXHR, textStatus, errorThrown) {
    //action here
});

如何聲明原型具有donefail事件(即使這是使用的正確術語),並確保它們在原型邏輯內的條件下被觸發?

我想要的電話將是這樣的:

var o = myObj({
    parma1: 'a',
    param2: 'b'
})
.done(function() {
    //action here
});
.fail(function() {
    //action here
});

我希望這是有道理的,因為我不知道此過程的正確術語是什么:(

我正在使用jQuery,因此,如果有使用jQuery的更好的解決方案,那就很好。

我想您想將此用於異步任務。 這是一個有點類似的解決方案:

var o = {
    parma1: 'a',
    param2: 'b',
    doAsyncStuff: function(complete, error){

        var someData = 0;        

        setTimeout(function(){
            someData = 1;
            complete(someData);
        }, 500);

        //or if something went wrong:
        //error(someErrorData);
    }
}

o.doAsyncStuff(function(data){
    console.log('complete', data);
}, function(data){
    console.log('error', data);
});

http://jsfiddle.net/pA99q/1/

根據要求,使用延遲對象的更新版本。 如果您可能需要progress ,我也讓自己自由地包括progress

var task = (function($){

    var dfd = $.Deferred(),
        cls = function(){

            console.log('param passed:', arguments);

            for(var i = 0; i < 5; i++){

                var count = 0;

                setTimeout(function(){   

                    count++;

                    dfd.notify({ msg: 'interation ' + count + ' complete' });

                    if(count === 5)
                        dfd.resolve({ something: 1 });

                    //if anything goes wrong, 
                    //you can always reject the deferred:
                    //dfd.reject(args); 

                }, 1000 * i);

            }
        };

    cls.prototype = {
        done: dfd.promise().done,
        fail: dfd.promise().fail,
        always: dfd.promise().always,
        progress: dfd.promise().progress
    };

    return cls;

})(jQuery);

var t = new task({ foo: 'bar' }, 123, 'baz');

t.progress(function(data){
    console.log('progress:', data);
}).done(function(){
    console.log('done');
}).fail(function(){
    console.log('fail');
}).always(function(){
    console.log('always');
});

http://jsfiddle.net/hGFbt/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM