Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to abstract a JavaScript library?

Tags:

javascript

What would be the best way to abstract away any given JavaScript framework (jQuery, MooTools etc.), that sits on the bottom of the framework stack? Essentially, I would like to have a situation where I could swap out the library, do changes only to one layer of the framework (not to every module, for example), and the whole thing could be up and running again.

So, every module should call a framework function(s), which would then be routed to the library.

like image 264
crappish Avatar asked Sep 14 '10 11:09

crappish


1 Answers

You may want to use something like the Adapter Pattern. Create your own interface, exposing the methods that you will be using in your application, and then create an adapter for each toolkit that you would like to support (jQuery, MooTools, YUI, etc). Your own interface would then route the method calls to the specific adapters.

If you were to support a new toolkit, all you'd have to do is to write a new adapter that translates methods from your own interface, to the methods of the specific toolkit.

This is something that Ext JS currently does. You can choose which adapter to use (jQuery, YUI, etc) behind the method calls of the framework. For example: Ext.getCmp() would use the jQuery.$() when using the jQuery adapter. However, it is often not a very easy one-to-one mapping.

Ext JS started its life as an extension to the Yahoo UI javascript library. At that time, Ext relied on YUI for all of its low-level cross-browser code. Now that Ext is a standalone JavaScript library, you have the choice of substituting YUI for other JavaScript libraries such as Prototype, or jQuery. The source files that map the low-level Ext API around other JavaScript libraries (or Ext's own base library) are known as adapters and they live in the source/adapter subdirectory. When you include Ext in your website you choose which adapter you want to use.

From: Ext JS Manual: Source Overview

like image 148
Daniel Vassallo Avatar answered Oct 21 '22 07:10

Daniel Vassallo