When would I use JQuery.Callbacks?

后端 未结 6 1491
忘掉有多难
忘掉有多难 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:17

    It seems that $.Callbacks began as an implementation detail: a means to manage lists of functions and to call all the functions in a given list with the same arguments. A little like C#'s multicast delegates, with additional features, like the flags you can pass to customize the list's behavior.

    A good example might be that jQuery uses $.Callbacks internally to implement its ready event. bindReady() initializes a callback list:

    readyList = jQuery.Callbacks( "once memory" );
    

    Note the once and memory flags, that ensure the callback list will only be called once, and that functions added after the list has been called will be called immediately.

    Then, ready() adds the specified handler to that list:

    ready: function( fn ) {
        // Attach the listeners
        jQuery.bindReady();
    
        // Add the callback
        readyList.add( fn );
    
        return this;
    }
    

    Finally, the callback list is fired when the DOM is ready:

    readyList.fireWith( document, [ jQuery ] );
    

    All the ready handlers are called in the context of the same document with the same reference to the global jQuery object. They can only be called this once, and additional handlers passed to ready() will be called immediately from then on, all of this courtesy of $.Callbacks.

提交回复
热议问题