MochiKit is awesome. I’ve only begun to scratch the surface of the power in this framework.
During my demo I had a hard time explaining what the partial function does. I have never been a Python developer, so MochiKit’s influence is foreign to me. I do appreciate the simplicity of the syntax.
Partial is aptly named. It is basically a partial function call, wrapped in an object. Why would you want this, I hear you say? Consider the following:
// $('ctrlid') is MochiKits alias of document.getElementById('ctrlid')
$('txtbox').onchange = filterText('some input'); //wrong! the function will be called immediately!
$('txtbox').onchange = function() //need an inline function wrapper to make the function call
{
filterText('some input');
}
$('txtbox').onchange = partial(filterText, 'some input'); //partial separates the function from the argument(s)
In this example, the top line is setting the onchange event handler of a textbox to a function call. But Javascript doesn’t know that you want a function pointer here, it looks like you want to call the method and return something. So the solution that you can do is write a single function that wraps the function call that you want to make. This can be done inline like I do above. Partial comes in and cleans up those 3 lines and pushes them into 1 line.
Next take a look at this:
function startsWith(character, target)
//searches target for character, if found... returns true
var startsWithCapitalB = partial(startsWith, 'B');
alert(startsWithCapitalB('Ben')); //true
alert(startsWithCapitalB('Henry')); //false
Here you see where partial gets its name. You can partially apply a function with partial and get a function variable returned!
Partial is incredibly powerful when applied with other functional programming methods like map.
Now playing: Modest Mouse - Black Cadillacs
I'm Ben Scheirman. I am a .NET software developer with a strong interest in agility. I work as a Principal Consultant with Sogeti.
Read more here.
email me
Ads by The Lounge
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.