Created
March 24, 2015 20:13
-
-
Save barneycarroll/5b027897c6f07f131609 to your computer and use it in GitHub Desktop.
POC for a component which can also be used as an extension to the Mithril view language by patching m
This file contains hidden or 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
var m = require( 'mithril' ); | |
var bidi = { | |
m : ( function(){ | |
function patch(){ | |
var node = m.apply( undefined, [].slice.call( arguments ); | |
if( node.attrs.bidi ){ | |
node = bidi.view( undefined, node.attrs.bidi, node ); | |
delete node.attrs.bidi; | |
} | |
return node; | |
} | |
for( var key in m ){ | |
patch[ key ] = m[ key ]; | |
} | |
return patch; | |
}() ), | |
view : function( ctrl, prop, node ){ | |
var type = node.tag === 'select' | |
? node.attrs.multi | |
? 'multi' | |
: 'select' | |
: node.attrs.type; | |
// Setup: bind listeners | |
if( type === 'multi' ){ | |
node.attrs.onchange = function(){ | |
prop( [].slice.call( this.selectedOptions, function( x ){ | |
return x.value; | |
} ) ); | |
} | |
} | |
else if( type === 'select' ){ | |
node.attrs.onchange = function( e ){ | |
prop( this.selectedOptions[ 0 ].value ); | |
}; | |
} | |
else if( type === 'checkbox' ){ | |
node.attrs.onchange = function( e ){ | |
prop( this.checked ) | |
}; | |
} | |
else { | |
node.attrs.onchange = node.attrs.oninput = function( e ){ | |
prop( this.value ); | |
} | |
} | |
if( node.tag === 'select' ){ | |
node.children.forEach( function( option ){ | |
if( option.attrs.value === prop() || option.children[ 0 ] === prop() ){ | |
option.attrs.selected = true; | |
} | |
} ); | |
} | |
else if( type === 'checkbox' ){ | |
node.attrs.checked = prop(); | |
} | |
else if( type === 'radio' ){ | |
node.attrs.checked = prop() === node.attrs.value; | |
} | |
else { | |
node.attrs.value = prop(); | |
} | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment