Creating your own JavaScript Library
来源:互联网 发布:js鼠标经过特效 编辑:程序博客网 时间:2024/06/05 06:07
http://www.mikedoesweb.com/2012/creating-your-own-javascript-library/
January 3rd, 2012 by Michael Jasper
One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).
My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.
I’d like to share what I learned from this project, and I hope you share back with me through the comments!
Finished project demo
Step 1: Identify the purpose of your library
This might just be one of the toughest parts of the whole process! If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries. I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling, etc. Knowing this, it is tempting to have lofty goals for your own library. One piece of advice: Don’t.
Pick one particular function, or aspect of web development/design that you would like your library to handle. Pick a niche need, and be happy with yourself when you fill it.
I decided my library would be a simple way to manipulate elements visually. At this point, I didn’t quite know how — but all you need is the kernel of the idea.
Step 2: Mock-up how would use the library
You always mock-up a webpage before you start building it right? Whether on paper, Photoshop, or even in code, it helps to pretend what the finished product will look like before you build it. It helps you to see obvious bugs, conflicts, and unwanted interactions you don’t catch when looking at the problem mentally.
Have you ever mocked-up your code? Write some implementation, pretending that the class or object you are dealing with exists. Trust me, it will solve problems!
I want my library to do visual stuff with elements, and I like how jQuery looks. How about this?
Looking at my pretend implementation, I can see 1 problem and a hand-full of design implementation points.
The problem: $
as a function name is likely to conflict with lots of other libraries. Through some Googleing, I learn at StackOverflow that functions must start with a $ (dollar-sign) _ (underscore) or letters.
We can also tell some design patterns:
_
is the function name_
must accept one or more parameters_
should return itself so that a dot-operator will work_
must control its scope so that we can have more than one_()
on a page- dot-operator methods must also return the
_
object for chaining
Step 3: Code up an outline
At this point, we know enough about the goal of our library, and how we will implement it, to begin outlining the structure of our library.
It may be useful for some (me) to review javascript function/object prototyping.
Step 4: Fix-up the constructor
Now don’t try and run your code just yet: we have a pretty big scope issue (besides no functionality):
When our _() function returns this , it is actually returning the entire window, or the global scope. Therefore, when we call _().toggle() , we are asking the browser to call the toggle() method which belongs to the window. Obviously this fails.
This problem can be solved by recursively creating another _
object using the new
keyword.
What is the new keyword in JavaScript?
For an in-depth look at this problem, read more about JavaScript constructors
Next to implement in our constructor: making the _()
represent an element with some bonus error prevention.
First, we create an about
object that will be returned, if the implementation doesn’t specify an element id. Next, we check if the id parameter was sent, and then create a variable to contain that element.
Here is a final version of the _() constructor:
Step 5: Prototype method implementation
This step is pretty fun: being creative, and implementing what you want your library to actually do!
I mentioned earlier that I wanted my library to do some visual manipulation of elements.Make a list of what you want to do. I came up with the methods:
- hide ()
- show ()
- bgcolor (color)
- val (value)
- toggle ()
- size (height, width)
The depth of this step depends on the functionality of your library. Mine were rather trivial to implement:
Demo or download the finished library here
Part 2 – Event Handling
Final thoughts
Writing my own small library was a good way for me to learn about JavaScript. One of the great ways to learn more is to study the code of other libraries and see how they work.
Did you use this tutorial to create your own library? I would really like to hear about it. Please leave me a comment below.
Cheers!
Update
Stack Overflow user W3Geek asked a question about part of this tutorial. Visit his question: How do these pieces of code function exactly? His question is focused on Step 4 about the object constructor. User Leland Richardson does an excellent job explaining this further — I’d direct you to his thorough explanation rather than duplicating it here.
- Creating your own JavaScript Library
- Creating Your Own Procedures
- Creating Your Own Validation
- Using JavaScript in PeopleSoft: Creating your own dialog boxes
- Creating Your Own Java Annotations
- Start your own JavaScript library using webpack and ES6
- Creating Your Own Widgets using SWT
- Creating your own SAP Customized Main Menu
- Creating Your Own Rails API Documentation
- spring boot--creating your own auto-configuration
- Reporting Crashes in IMVU: Creating Your Very Own Symbol Server
- Creating your own ODS Style Template for PDF Output
- Creating and Using Your Own Delegates in Objective-C
- Test your own form/library from a specific directory
- [zt] Creating your own GTK+ widget & adding it to Glade Palette
- Android:Creating Your Own Spelling Checker Service(创建拼写检查服务)
- Creating Your Own Document Management System With SharePoint 使用SharePoint创建你自己的文档管理系统
- How to distribute your own Android library through jCenter and Maven Central from Android Studio
- Java中匿名内部类总结
- Codeforces Round #311 (Div. 2) A,B,C,D,E
- 希尔排序算法
- Project Euler 46 solution optimized using C++ meta-programming
- 双色球计算程序
- Creating your own JavaScript Library
- Karhunen-Loeve Transform (KLT) 原理及PCA应用
- [Leetcode 237, Easy] Delete Node in a Linked List
- 迭代算法求平方根
- IE配置PAC动态代理
- IEEE802系列标准小结
- Leetcode NO.237 Delete Node in a Linked List
- 每日一类之String类
- 数学运算类和包装类