Skip to content

Instantly share code, notes, and snippets.

@desbo
Last active July 13, 2016 14:31
Show Gist options
  • Save desbo/1b110dc309b2882382c4ef5d720bc2db to your computer and use it in GitHub Desktop.
Save desbo/1b110dc309b2882382c4ef5d720bc2db to your computer and use it in GitHub Desktop.
steady on
function Queue() {
this.queue = [];
}
/**
* Add an item to the queue
*
* @param {Anything} item item to add
* @return {Number} queue length
*/
Queue.prototype.enqueue = function(item) {
return this.queue.push(item);
};
/**
* Take the first item from the queue
*
* @return {Anything} the item
*/
Queue.prototype.dequeue = function() {
return this.queue.shift();
};
/**
* Check if the queue is empty
*
* @return {Boolean}
*/
Queue.prototype.empty = function() {
return this.queue.length === 0;
};
return Queue;
// -------------------
var q = new Queue();
var running = false;
function readHeight(el) {
return fastdom.read() {
var style = getComputedStyle(el);
return el.offsetHeight + parseInt(style.marginTop) + parseInt(style.marginBottom);
};
}
/**
* Process the insertion operation:
*
* 1. Calculate the original height of the container
* 2. Apply the insertion function
* 3. Calculate the new height of the container
* 4. Adjust the scroll position to account for the new container height
*
* @param {Object} insertion
*/
function go(insertion) {
running = true;
readHeight(insertion.container).then(function(originalHeight) {
return fastom.write(function() {
insertion.cb();
}).then(function() {
return readHeight(insertion.container);
}).then(function(newHeight) {
return newHeight - originalHeight;
});
}).then(function(offset) {
window.scrollTo(0, window.scrollY + offset);
}).then(function() {
if (q.empty) {
running = false;
} else {
go(q.dequeue);
}
});
}
/*
* Insert an element into the page
* Use if your element doesn't exist and is inserted into a container
* ** Don't use fastdom - it is handled in this utility **
* @param {HTMLElement} insertionContainer The element that the component is being inserted into
* @param {Function} insertionCallback Should contain all functionality that displays and lays-out the element
*/
function insert(container, cb) {
q.enqueue({
container: container,
cb: cb
});
if (!running) {
go(q.dequeue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment