Last active
December 21, 2015 03:28
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
})); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any reason why you're creating a second closure? You can do without the
once
function.