Using monocle mustache for chaining.
Mike Samuel
mikesamuel at gmail.com
Sat Nov 12 12:46:06 PST 2011
2011/11/11 Erik Arvidsson <erik.arvidsson at gmail.com>:
> We've all looked at jQuery code and envied the conciseness of its chaining
> APIs. Most of us also looked at it and thought; Yuk, making everything a
> method of jQuery and always return the jQuery object is ugly.
>
> However, I (with some help) realized that the .{ operator can be used to
> solve most of these chaining scenarios without any changes to any API.
>
> Take this jQuery sample code:
>
>
>
>
> $('#my-element').
>
>
>
> css({
>
>
>
> 'color': 'red',
>
>
>
> 'padding': '5px'
>
>
>
> }).
>
> text('Hello');
>
>
>
>
> With the 'stache:
>
>
>
> document.querySelector('#my-element').{
>
>
>
> style.{
>
>
>
> 'color': 'red',
>
>
>
> 'padding': '5px'
>
>
>
> }.
>
> textContent: 'Hello'
>
>
>
> };
>
> One could easily see some extensions to make this even more useful. For
> example allowing method calls and member lookups etc would sweeten the deal.
> Here is a more advanced example that assumes we have some useful properties
> on the returned DOM collections:
> jQuery:
>
>
> $('#myTable').
>
> find('.firstColumn').
>
> css({'background': 'red', 'border': '2px solid black'}).
>
> text('first column').
>
> end().
>
> find('.lastColumn').
>
> css('background','blue').
>
> text('last column');
>
>
> With the 'stache:
>
>
> document.querySelector('#myTable').{
>
> querySelectorAll('.firstColumn').{
>
> style.{background: 'red', border: '2px solid black'},
>
> textContent: 'first column'
>
> },
>
> querySelectorAll('.lastColumn').{
>
> style.{background: 'blue', border: '2px solid black'},
>
> textContent: 'last column'
>
> }
>
> };
>
>
>
> I've also been told that this is just another form of Smalltalk's message
> cascade.
>
> --
> erik
Does this depends on object key iteration order being defined as
insertion order?
Since an object can only have one property with a given name can
chaining express patterns that the mustache can't?
I.e. how would a chain with two calls to methods with the same name translate:
foo.bar(x).baz(y).bar(z)
?
More information about the es-discuss
mailing list