jquery4u.com - Archives (avril 2015)

1 jQuery Fan Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets.

Le: 29 04 2015 à 23:30 Auteur: David Catuhe

While designing Babylon.js v2.0 (a library for building 3D on the web), I recently found myself wishing that more APIs were fluent – that is, I wish the community could more easily read, understand, and build upon the work while spending less time in the tech docs. In this tutorial, I’ll walk through Fluent APIs – what to consider, how to write them, and cross-browser performance implications.

fluent01 - should i

What Makes an API Fluent?

A fluent API, as stated by this Wikipedia article, is an implementation of an object-oriented API that aims to provide for more readable code. jQuery, for example, is a great example of what a fluent API allows you to do:

[code language="js"] $('
') .html("Fluent API are cool!") .addClass("header") .appendTo("body"); [/code]

A fluent API lets you chain function calls by returning the this object.

We can easily create a fluent API like this:

[code language="js"] var MyClass = function(a) { this.a = a; } MyClass.prototype.foo = function(b) { // Do some complex work this.a += Math.cos(b); return this; } [/code]

As you can see, the trick is just about returning the this object (a reference to the current instance in this case) to allow the chain to continue.

If you are not aware of how the this keyword works in JavaScript, I recommend reading this great article by Mike West.

We can then chain calls:

[code language="js"] var obj = new MyClass(5); obj.foo(1).foo(2).foo(3); [/code]

Before trying to do the same with Babylon.js, I wanted to be sure that this would not generate some performance issues.

So I did a benchmark!

Continue reading %JavaScript like a Boss: Understanding Fluent APIs%