When would I use JQuery.Callbacks?

后端 未结 6 1444
忘掉有多难
忘掉有多难 2021-01-30 01:34

I was looking through new stuff added to jQuery 1.7 and I saw they now have jQuery.Callbacks() http://api.jquery.com/jQuery.Callbacks/.

The documentation shows you how

6条回答
  •  花落未央
    2021-01-30 02:13

    An (almost) out of the box jQuery Pub/Sub system

    This is IMHO the most interesting application, and since it was not clearly stated in the answers (although some do make allusion to the usage), I am adding it to this relatively old post.

    NB: The usage is clearly indicated, with an example, in the jQuery docs, but I guess it was added after the question was posted.

    Pub/sub, aka the observer pattern, is a pattern which promotes loose coupling and single responsibility in an application. Rather than having objects calling directly the methods of other objects, objects instead subscribe to a specific task or activity and are notified when it occurs. For a more detailed explanation of the benefits of using the Pub/Sub pattern, you can check Why would one use the Publish/Subscribe pattern (in JS/jQuery)?.

    Sure, this was possible with custom events using trigger, .on() and .off(), but I find jQuery.Callbacks to be a lot more suitable to the task, producing cleaner code.

    Here is the example snippet from the jQuery documentation:

    var topics = {};
     
    jQuery.Topic = function( id ) {
        var callbacks,
            method,
            topic = id && topics[ id ];
     
        if ( !topic ) {
            callbacks = jQuery.Callbacks();
            topic = {
                publish: callbacks.fire,
                subscribe: callbacks.add,
                unsubscribe: callbacks.remove
            };
            if ( id ) {
                topics[ id ] = topic;
            }
        }
        return topic;
    };
    

    And a usage example:

    // Subscribers
    $.Topic( "mailArrived" ).subscribe( fn1 );
    $.Topic( "mailArrived" ).subscribe( fn2 );
    $.Topic( "mailSent" ).subscribe( fn1 );
     
    // Publisher
    $.Topic( "mailArrived" ).publish( "hello world!" );
    $.Topic( "mailSent" ).publish( "woo! mail!" );
     
    // Here, "hello world!" gets pushed to fn1 and fn2
    // when the "mailArrived" notification is published
    // with "woo! mail!" also being pushed to fn1 when
    // the "mailSent" notification is published.
     
    /*
    output:
    hello world!
    fn2 says: hello world!
    woo! mail!
    */
    

提交回复
热议问题