Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Last active December 21, 2015 03:28
/**
* Example using a Deferred object
*/
(function(){
var deferred;
$(document).on('click', '.show-scores', setupOnce(function(){
// $.getJSON returns a $.Deferred object
deferred = $.getJSON('/scores.json');
}, function() {
deferred.done(function(json) {
// fancy score handling
});
}));
})();
/**
* Prepare a modal box or a template once and fill it in at each invocation
*/
(function(){
var modal;
$(document).on('click', '.modal-trigger', setupOnce(function(){
modal = new Modal();
}, function() {
modal.title = this.source.title;
modal.show();
}));
})();
/**
* Runs `setup` on the first invocation
* Runs `callback` on each invocation
* @link https://gist.github.com/lavoiesl/6241939
*
* @param Function setup
* @param Function callback
*/
function setupOnce(setup, callback) {
var ran = false;
return function() {
if (!ran) {
setup.apply(this, arguments);
ran = true;
}
return callback.apply(this, arguments);
}
}
@keeto
Copy link

keeto commented Dec 8, 2013

Any reason why you're creating a second closure? You can do without the once function.

function setupOnce(setup, callback) {
  var ran = false;
  return function() {
    if (!ran) {
      setup.apply(this, arguments);
      ran = true;
    }
    return callback.apply(this, arguments);
  }
}

@lavoiesl
Copy link
Author

I have no idea. Thanks :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment