#Kamehameha — the way you perform infinite loading
Kamehameha is a kind of energy attack in the Dragon Ball series, and is Goku's signature technique.
Let's simplify kamehameha and compare it with infinite loading:
This toy class defines an action flow of infinite loading by applying the kamehameha metaphor. It Helps user to focus on the business logic: event lisening, loading and rendering.
-
Create a GoKu. (GoKu is the character who can perform kamehameha with great power. "Kamehameha" is hard to spell. "Goku" should be more human-friendly.)
var options = { watch: function (next) {} ,shouldTrigger: function (event) {} ,onHold: function (next) {} ,onEmit: function (next) {} ,restingSeconds: <number> } var goku = new Goku(options);
-
Decide a watching target (options.watch). By default, he watches on window scroll event
-
Decide a triggering condition (options.shouldTrigger). By default, he triggers the action while page reaches bottom
// trigger it once the distance to bottom is less than 100px shouldTrigger: function (event) { var heightViewport = $(window).height(); var distanceFromViewportTopToPageBottom = $(document).height() - $(document).scrollTop(); return (distanceFromViewportTopToPageBottom - heightViewport) < 100; }
-
Decide a callback to perform ajax requesting (options.onHold).
// load 10 images from http://lorempixel.com/ onHold: function(counter, next) { // ... // (new Image()).src = 'http://lorempixel.com/...'; // ... next(); }
-
Decide a callback to perform data rendering (options.onEmit).
// render each loaded image onHold: function(counter, next) { // ... // $canvas.append(imageObject); // ... next(); }
-
Decide how long to take a rest (options.restingSeconds). By default, it's one second.
-
Ask Goku to study what you teach and start to work
goku.study();