Chainvas: an elegant and miniature crutch that adds method chaining to any API

  • Tutorial
Thanks to the jQuery library, since about 2006 (that is, about five years ago) no one needs to explain what method chaining is : this is the same programming technique in which the methods of an object can be called one after another in a chain, as in jQuery.

The main advantage of this technique is the noticeable saving in the efforts of the programmer. With it, the programmer does not have to re-write the name of the object repeatedly in this manner:
obj.шмяк();
obj.тыдыжжь();
obj.ынц();

Instead, the programmer can call all methods in a chained fashion - on one line:
obj.шмяк().тыдыжжь().ынц();

If it seems to him that this type of recording is less readable by a person than the previous one (especially when the methods have parameters, sometimes quite extensive), then the programmer can write the names of methods from a new line (this allows JavaScript), but still save on the name object:
obj
   .шмяк(параметр1, параметр2, …)
   .тыдыжжь(параметр1, параметр2, …)
   .ынц(параметр1, параметр2, …);

In practice, the possibility of such a technique is ensured by the fact that no object method returns an undefined value . Instead, if the method is a command, not a request (that is, it performs some action, but does not return some value), then at the end the author of the library writes return this ” - this provides the ability to record the call of several commands in a row in the form chains.

As far as I know, the established Russian equivalent of the English phrase “method chaining” does not yet exist. Probably, we can talk about the "chain" or, for simplicity, about the "chain" form of method calls.

The convenience of a chain call is addictive. Well, the truth is: it’s enough to program a couple of weeks or two on jQuery - and ordinary APIs begin to annoy, even enrage, with their antediluvian impossibility of a chain call. It also lacks the ability to set their properties as an object passed to a method like .css ({color: 'red', 'line-height': 1}) in jQuery.

Imagine, for example, how unusually convenient it would be if you were on canvas () could draw chain calls in this manner:
ctx.beginPath()
   .prop({
      lineWidth: 2,
      strokeStyle: '#333'
   }).moveTo(0,0)
   .bezierCurveTo(50,50, 80,80, 100,100)
   .stroke().closePath();

And a tool for just such chain calls has come about - thanks to Lea Verou. Here it is: The Chainvas library weighs only ≈1⅓ kilobytes after processing with a minifier, but meanwhile, using its methods, you can provide a wrapper around all (or only some) methods of any object, providing a chain call to them. A couple of ready-made additional modules are also attached to it, one of which (with a volume of 348 bytes) defines a wrapper around the API DOM, and the other (with a volume of 406 bytes) defines a wrapper of canvases (

[Chainvas]

)

DOM wrapping allows you to make chain calls like the following:
// цепной вызов DOM (объектной модели документа):
document.body.appendChild(
   document.createElement('a')
      .prop({
         'href': 'http://leaverou.me',
         'innerHTML': 'Lea Verou',
         'title': 'Visit this awesome blog!',
         'onclick': function(evt){
            alert('gotcha!');
         }
      })
      .setAttribute('data-unicorns', '42')
      .addEventListener('mouseover', function(){
         alert('don’t do this');
      }, false)
);
// цепной вызов CSSOM (объектной модели стилей):
var css = document.body.style.prop({
   color: '#245',
   fontFamily: 'Georgia, serif',
   textDecoration: 'underline'
}).removeProperty('text-decoration').cssText;
// цепной вызов методов classList:
element.classList
   .add('foo')
   .add('bar')
   .toggle('baz');

It looks good - but, of course, with jQuery, nobody needs all this. I would never bother with document.createElement ('a') instead of just $ (' ') , for example.

And here is a wrapper for canvas ()- This is a completely different matter. It not only provides a chain call to canvas methods (an example of which I gave before I mentioned Chainvas), which is not in jQuery, but also defines two useful helper methods: circle (x, y, radius) for drawing circles and roundRect (x, y, width, height, radius) to draw rounded rectangles. (Here I call "drawing" the definition of the outline's outline, after which an additional call to stroke () or fill () will nevertheless be required for the actual display.)

Sweet, sweet syntactic sugar.

It is not surprising, therefore, that the author herself called the library “Chainvas”.

Also popular now: