开发者

Good Practices in JavaScript API Development

What's a good approach to designing a JavaScript API?

I'm relatively开发者_JAVA百科 new to JavaScript and learning the key good features of the language, mostly from "JavaScript: The Good Parts". Currently, I'm designing a web based tool to teach Statistics. The code base is getting unwieldly in part because I don't understand how to design a JavaScript API.

My background is in Java and C++ and am used to designing interfaces then implementing those interfaces independently. Obviously, this doesn't work well in JavaScript.

Thanks for any help and suggestions.

Update: Final version of the tool here: http://www.lock5stat.com/statkey/index.html


In my opinion, if you're using jQuery, the best solution is to divide your application into jQuery plugins and UI widgets. Plugins are great way to organize the code, you can reuse them in other applications and you can also release them separately.

You can write your applications as a tree of plugins. You can think about plugins like classes in C++/Java with aggregation but not inheritance.

Notes about code: in MAIN.bootstrapPlot function you use document.createElement, you should use jQuery like in the rest of the code, and check Canto library for Canvas.


John Resig has a scathing critique of the NodeIterator API. Although it's a review of one specific API, it provides some insights into (at least what he believes) makes for a good tool.


I think its the same as developing any API regardless of language, keeping in mind the language features.

  1. As you point out interfaces don't make much sense in javascript, but it is object oriented, so you can divide your functionality into 'classes', use design patterns, etc.

  2. Documentation. You can document a javascript 'class' just like you document any API.

  3. Even though there is no native support for interfaces or abstract classes in js, you can still enforce the principles. For example, you can create an 'abstract class' by defining an object with methods that throw errors, that way subclasses will error out if they are not implemented properly. Anything that uses an interface can do a simple check to see if the necessary methods are in place on init. Note that some js people will frown upon this, pointing out that js is loosely typed and dynamic, and should be used that way.

Note that i put 'class' in quotes because javascript has no notion as such. The other thing you can do is look to existing APIs like Sencha or jQuery to get some ideas. Sencha feels like an API a server side developer would be used to (look at their docs).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜