开发者

Javascript - Passing and finding callback functions

I am writing a small module which will have several different aspects to it, all based around ajax calls. I want to allow the ma开发者_StackOverflow中文版in ajax functions i.e beforeSend, success, complete etc (I am using jQuery) to be customizeable.

What is the best way to do this?

I currently have an options object in the module which can be extended with an options object passed to an init function. In here, I am passing a 'callbacks' object with nested ojects for each different type of action as in...

        var insertCallbacks = {

        before : function() {

        },
        success : function() {

        },
        error : function() {

        },
        complete : function() {

        }
    };

    var updateCallbacks = {
        before : function() {

        },
        success : function() {

        },
        error : function() {

        },
        complete : function() {

        }
    };

    var callbacks =  {
        insert : addCallbacks,
        update : removeCallbacks    
    };

   MY_MODULE.init( {callbacks : callbacks} );

The problem is this then becomes a bit messy, testing for the existence of each of these methods on the ajax callbacks.

Can anyone offer any advice on a good/better pattern for this.


I would go with custom events rather than callbacks. So in your module you will have code like:

MY_MODULE.trigger('updateComplete');

and in all parts outside of module (as well as inside if needed), you bind handlers (now they are callbacks):

 MY_MODULE.bind('updateComplete', function() { 
    alert('update completed'); 
 } );

Custom events in jQuery open doors to complex behaviors, or google any other article. Custom events will help you to keep code structured, and easier to test

ADD ON: with callbacks you need always to check if there is any, so you code becomes

if ( callbacks && callbacks.insert ) {
    callbacks.insert();
}

improving your module functionality, and enhancing it, one day you get a situation that few callbacks should be passed for the same situation (e.g. two entities or UI components are interested in module 'updating')... It will make your job too difficult. With events you always have one code line

MY_MODULE.trigger('updateComplete');

with no conditions to check if there is any handler attached (interested in an event), and you can have as many as needed handlers for the same event.


Just do the same thing jQuery does. Let your module fire events (via trigger()) and attach handlers to these events when necessary (via bind()). This way you do not have to check inside your module what functions are listening (or if at all).

Since your code does not contain anything I could use for a sample, it's kind of hard to add code to this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜