Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created November 13, 2014 19:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barneycarroll/efd0c8768dc9813ce656 to your computer and use it in GitHub Desktop.
Save barneycarroll/efd0c8768dc9813ce656 to your computer and use it in GitHub Desktop.
A grid vm for Mithril
'use strict';
function grid( axis ){
var items = [];
var pending;
var container;
function queue(){
if( pending ) ( window.cancelAnimationFrame || window.clearTimeout )( pending );
pending = ( window.requestAnimationFrame || window.setTimeout )( apply, 16 );
}
function apply(){
var total = container.clientWidth;
var occupied = items.reduce( function( accumulator, item, index ){
return accumulator + ( item.shouldExpand ? 0 : item.el.clientWidth );
}, 0 );
var remaining = total - occupied;
if( remaining < 0 ){
items.forEach( function equalize( item ){
item.el.style.width = total / items.length + 'px';
} );
}
else {
items
.filter( function shouldEpand( item ){
return item.shouldExpand;
} )
.forEach( function distribute( item, index, array ){
item.el.style.width = remaining / array.length + 'px';
} );
}
}
function setup(){
window.addEventListener( 'resize', apply, false );
}
function teardown(){
window.removeEventListener( 'resize', apply, false );
}
return {
container : function registerContainer( axis ){
items = [];
return function config( el, init, context ){
if( !init ){
container = el;
setup();
context.onunload = teardown;
}
queue();
};
},
item : function registerItem( shouldExpand ){
var item = {
shouldExpand : shouldExpand
};
var index = items.push( item );
return function config( el, init, context ){
if( !init ){
item.el = el;
context.unload = function unregister(){
items.splice( items.indexOf( item ), index, 1 );
};
}
};
}
};
}
module.exports = grid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment