Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Library Design

Tags:

javascript

I have a general question about the design of JavaScript Libraries.

I am trying to consolidate common methods into one js file so they can be reused by different scripts.

I have taken a look at how the JSON library is structured and believe it was a good approach. JSON for Javascript.

So they start off creating an instance of the class:

if (!this.JSON) {     this.JSON = {}; } 

Then they do this:

(function () {     if (typeof JSON.stringify !== 'function') {         JSON.stringify = function (value, replacer, space) { 

This is works perfect if you just want to do JSON.[function_name], but what if I want to have a more structured library such that I want: JSON.[subgroup].[function]. How would I structure my JS library in such a way?

Any links to resources are greatly appreciated, thanks.

like image 708
JSMan2034 Avatar asked May 17 '10 14:05

JSMan2034


People also ask

Which library is used for JavaScript?

js (also known as ReactJS or React) is an open-source, front-end JavaScript library. It was created in 2013 by Jordan Walke, who works at Facebook as a software engineer.

How does a JavaScript library work?

Generally speaking, JavaScript libraries are collections of prewritten code snippets that can be used and reused to perform common JavaScript functions. A particular JavaScript library code can be plugged into the rest of your project's code on an as-needed basis.

Does JavaScript have built in libraries?

While other platforms, like Android or iOS, clearly state what a library is, what format it must have and how it should be integrated into a project, JavaScript doesn't provide any built-in mechanism.


2 Answers

I would recommend you to follow the Module Pattern in JavaScript instead of following JSON's pattern strictly. Your subgroup is actually referring to sub-modules. Take a look at the following excellent article:

Ben Cherry's JavaScript Module Pattern In-Depth

Other resources you should probably go through:

  • John Resig's Learning Advanced JavaScript
  • Seven JavaScript Things I Wish I Knew Much Earlier In My Career
  • The Seven Deadly Sins Of JavaScript Implementation
like image 191
sirhc Avatar answered Sep 19 '22 21:09

sirhc


There are problems with the module pattern. See http://snook.ca/archives/javascript/no-love-for-module-pattern. I used to use it before but stopped. Now I just tend to keep it simple. If you really want sub-namespacing you can make a simple namespace function for the job.

See http://blogger.ziesemer.com/2008/05/javascript-namespace-function.html

like image 30
lenkite Avatar answered Sep 22 '22 21:09

lenkite