Using monocle mustache for chaining.

Erik Arvidsson erik.arvidsson at gmail.com
Fri Nov 11 10:50:16 PST 2011


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111111/221ea5a3/attachment-0001.html>


More information about the es-discuss mailing list