When would I use JQuery.Callbacks?

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

    To expand on @Rockets answer a bit and clear up some confusion:

    The reason that one might need to use jQuery's $.Callbacks is multifaceted:

    1. The user has a lot of code in one function and wants to split it up
    2. They take that information and send it through the jQuery callback function which then allows them to have split their code into better manageable pieces with which to work with.
      So (for example) if you look at @Rocket's code:

      var clickCallbacks = $.Callbacks();
      
      clickCallbacks.add(function() { //one one function piece
          //parse and do something on the scope of `this`
          var c = parseInt(this.text(), 10);
          this.text(c + 1);
      });
      clickCallbacks.add(function(id) { //add a second non-related function piece
          //do something with the arguments that were passed
          $('span', '#last').text(id);
      });
      
      $('.click').click(function() {
          var $ele = $(this).next('div').find('[id^="clickCount"]');
          clickCallbacks.fireWith($ele, [this.id]); //do two separate but related things.
      });
      
    3. What you can now have is multiple callback batches of function which you can now call whenever you deem it be necessary without the need to make so many changes throughout out your code.

提交回复
热议问题