JavaScript API Design Principles

Source: Internet
Author: User
Tags event listener what parameter

NET + Offline Salon | Mobile app Mode innovation: give you a reason to do the app >>

Good API design: In the self-description, at the same time to achieve abstract goals.

Well-designed APIs allow developers to get started quickly, without the need to keep manuals and documentation often, or to visit the tech support community frequently.

Smooth interface

Method chain: Smooth and easy to read, easier to understand

  1. Common API Call methods: Change some colors, add event listener
  2. var elem = document.getElementById ("Foobar");
  3. = "Red";
  4. = "green";
  5. Elem.addeventlistener (' click ', Function (event) {
  6. Alert ("Hello world!");
  7. }, true);
  8. (conceived) method chain API
  9. Domhelper.getelementbyid (' foobar ')
  10. . SetStyle ("Background", "Red")
  11. . SetStyle ("Color", "green")
  12. . addevent ("click", Function (event) {
  13. Alert ("Hello World");
  14. });

Settings and get operations can be combined; the more methods, the more difficult the document may be to write

    1. var $elem = jQuery ("#foobar");
    2. Setter
    3. $elem. Setcss ("Background", "green");
    4. Getter
    5. $elem. GETCSS ("color") = = = = "Red";
    6. Getter, Setter merged
    7. $elem. CSS ("background", "green");
    8. $elem. CSS ("color") = = = = "Red";


The relevant interface maintains a consistent style, and a full set of APIs that convey a sense of familiarity and comfort will greatly reduce the developer's adaptability to new tools.

Naming this thing: both short and self-describing, and most importantly, maintaining consistency

"There is only a problems in computer science:cache-invalidation and naming things."
"There are only two headaches in the computer science: Cache invalidation and naming problems"
-phil Karlton

Choose a language that you like, and then continue to use it. Choose a style, and then keep that style.

Processing parameters

You need to think about how you can use the methods you provide, and whether they will be repeated calls? Why is the call repeated? How does your API help developers reduce repetitive calls?
Receiving map map parameters, callbacks, or serialized property names not only makes your API cleaner, it's more comfortable and efficient to use.

The JQuery css() method allows you to style the DOM elements:

    1. JQuery ("#some-selector")
    2. . CSS ("background", "Red")
    3. . css ("Color", "white")
    4. . CSS ("Font-weight", "bold")
    5. . css ("padding", ten);

This method can accept a JSON object:

  1. JQuery ("#some-selector"). CSS ({
  2. " Background": "Red",
  3. "COLOR": "White",
  4. " font-weight": "bold",
  5. "padding": ten
  6. });
  7. Bind events by passing a map map
  8. JQuery ("#some-selector"). On ({
  9. "click": Myclickhandler,
  10. "KeyUp": Mykeyuphandler,
  11. "Change": Mychangehandler
  12. });
  13. Binding the same handler function for multiple events
  14. JQuery ("#some-selector"). On ("Click KeyUp Change", MyEventHandler);

Processing type

When defining a method, you need to decide what parameters it can receive. We are not sure how people use our code, but can be more visionary and consider what parameter types are supported.

  1. The original code
  2. DateInterval.prototype.days = function (start, end) {
  3. return Math.floor ((end-start)/ 86400000);
  4. };
  5. The modified code
  6. DateInterval.prototype.days = function (start, end) {
  7. if (! ( Start instanceof Date)) {
  8. Start = new Date (start);
  9. }
  10. if (! ( End instanceof Date)) {
  11. end = new Date (end);
  12. }
  13. return Math.floor ((End.gettime ()-start.gettime ())/ 86400000);
  14. };

Adding a short 6 lines of code, our approach is powerful to receive Date objects, numeric timestamps, and even Sat Sep 08 2012 15:34:35 GMT+0200 (CEST) strings like this

If you need to ensure that the passed parameter type (string, number, Boolean) can be converted like this:

    1. function Castaway (some_string, Some_integer, Some_boolean) {
    2. Some_string + = "";
    3. Some_integer + = 0; //parseint (Some_integer, 10) more secure
    4. Some_boolean =!! Some_boolean;
    5. }

Handling undefined

To make your API more robust, you need to identify whether the actual undefined value is passed in, and you can examine the arguments object:

  1. function testundefined (expecting, someargument) {
  2. if (someargument = = = undefined) {
  3. Console.log ("someargument is undefined");
  4. }
  5. if (Arguments.length > 1) {
  6. Console.log ("However it is actually passed in");
  7. }
  8. }
  9. testundefined ("foo");
  10. Result: Someargument is undefined
  11. testundefined ("foo", undefined);
  12. Result: Someargument was undefined, but it actually came in.

Give the parameter a name

    1. Event.initmouseevent (
    2. "Click", True, true, window,
    3. 123, 101, 202, 101, 202,
    4. true, false , False, False,
    5. 1, null);

Event.initmouseevent This method is simply insane, without looking at the document, who can say what each parameter means?

Give each parameter a name and assign a default value.

  1. Event.initmouseevent (
  2. Type="click",
  3. Canbubble=True,
  4. Cancelable=True,
  5. View=window,
  6. Detail=123,
  7. screenx=101,
  8. screeny=202,
  9. clientx=101,
  10. clienty=202,
  11. Ctrlkey=True,
  12. Altkey=false,
  13. Shiftkey=false,
  14. Metakey=false,
  15. button=1,
  16. relatedtarget=null);

ES6, or Harmony has default parameter values and rest parameters.

Parameter Receive JSON object

Instead of receiving a bunch of arguments, you might as well receive a JSON object:

    1. Function Nightmare (accepts, async, beforesend, cache, complete,/ * etc 28 Parameters */) {
    2. if (accepts = = = "text") {
    3. //Ready to receive plain text
    4. }
    5. }
    6. function Dream (options) {
    7. options = Options | | {};
    8. if (options.accepts = = = "text") {
    9. //Ready to receive plain text
    10. }
    11. }

It's also easier to call:

    1. Nightmare ("text", true, undefined, false, undefined,/ * etc 28 parameters */);
    2. Dream ({
    3. Accepts: "text",
    4. Async: True,
    5. Cache: false
    6. });

Parameter Default value

Parameters are best with default values, which can be overridden by jquery.extend () and Protoype object.extend.

  1. var default_options = {
  2. Accepts: "text",
  3. Async: True,
  4. Beforesend: null,
  5. Cache: false,
  6. Complete: null,
  7. //...
  8. };
  9. function Dream (options) {
  10. var o = jquery.extend ({}, default_options, Options | | {});
  11. Console.log (o.accepts);
  12. }
  13. Dream ({async: false});
  14. Prints: "Text"


Callback (callbacks)

With callbacks, the API user can overwrite a portion of your code. Open up some features that you need to customize into configurable callback functions that allow API users to easily overwrite your default code.

Once the API interfaces receive callbacks, make sure they are documented and provide code examples.

Event (events)

The event interface is best known for its name, and the event name can be chosen freely to avoid the same names as the original event.

Handling Errors

Not all errors are useful for developer debug code:

    1. jQuery allows this to be written
    2. $ (document.body). On (' click ', {});
    3. Click the Times wrong
    4. TypeError: ((P.event.special[l.origtype] | | {}). Handle | | L.handler). Apply is not a function
    5. In JQuery.min.js on line 3

Such errors are painful to debug, do not waste the developer's time, tell them directly what is wrong:

    1. if ( (callback)!== ' [Object Function] ') { //See note
    2. throw New TypeError ("Callback is not a function!");
    3. }
    4. Remark: typeof callback = = = "function" There will be a problem on the old browser, and object becomes a function.


A good API is predictable, and the developer can infer its usage based on an example.

Modernizr ' s feature detection is an example:

A) the attribute name it uses is fully matched to HTML5, CSS concepts, and APIs

b) Each individual detection consistently returns a value of TRUE or False

    1. All of these properties return ' true ' or ' false '
    2. Modernizr.geolocation
    3. Modernizr.localstorage
    4. Modernizr.webworkers
    5. Modernizr.canvas
    6. Modernizr.borderradius
    7. Modernizr.boxshadow
    8. Modernizr.flexbox

A concept that relies on the familiarity of the developer can also achieve predictable purposes.

The jQuery ' s selector syntax is a notable example, and the CSS1-CSS3 selector can be used directly with its DOM selector engine.

    1. $ ("#grid") //Selects by ID
    2. $ ("Ul.nav > li") //All LIs for the UL with Class "Nav"
    3. $ ("ul Li:nth-child (2)") //Second item in each list

Proportional coordination

A good API is not necessarily a small api,api size to match its function.

For example, Moment.js, the famous date parsing and formatted library, can be called equalization, its API is both concise and functional clear.

A library of specific features, such as moment.js, is important to ensure that the API is focused and small.

Writing API Documentation

One of the hardest tasks in software development is writing documents, in fact everyone hates to write documents, complaining that there is no good documentation tool.

Here are some document auto-generation tools:

      • Yuidoc (Requires node. js, NPM)

      • JsDoc Toolkit (Requires node. js, NPM)

      • Markdox (Requires node. js, NPM)

      • Dox (Requires node. js, NPM)

      • Docco (Requires node. js, Python, Coffeescript)

      • Jsduck (Reqires Ruby, Gem)

      • JSDoc 3 (Requires Java)

JavaScript API Design Principles

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.