Things you need to pay attention to when developing jQuery plugins,
1. Make it clear that there is only one namespace for jQuery.
2. Understand that the options parameter is used to control the behavior of the plugin.
3. Provide public access to the default plugin settings.
4. Provide public access permissions to sub-functions.
5. Private functions must have private access
6. Support metadata plugin.
I will explain the above conditions one by one in the following example. After doing these things, we will create a simple plug-in that highlights text.
1. Make it clear that jQuery has only one namespace
In our example, we will name this plugin hilight,
That is, our plugin can be used through the following methods:
Why does the jQuery plugin only have one namespace? It may be a design requirement, or it may be more readable, or it may be for the object-oriented design pattern.
2. Understand the options parameters to control the behavior of the plugin.
Let us first clarify the colors of the foreground and background for our hilight plug-in. We should be able to allow these two options to be passed to the plugin's main function as option objects. For example:
Now the plugin can set the following properties:
3. Provide public access to the default plugin settings.
What we can improve here is to make the above code configurable and expandable. This way users who use this plug-in can override our options with minimal code. This is the benefit of starting to use function objects.
Now users can set the foreground attribute in their scripts with one line of code:
With the above code, we can set the foreground color of a certain DOM control to blue.
4. Provide public access permissions to sub-functions
This clause is similar to the above and can be a very interesting way to extend the functionality of your Plugin. For example: In lilight's plugin, we can define a function as format, and we can define the form of hilight's text. Our plugin code will appear as follows:
Here we can easily support another option object to override the default formatting through a callback function. That would be another great way to support customization.
5. Private functions must have private access
It is of course a very powerful feature that some options of the public plugin can be customized. But you need to consider which parts should be made public and which parts should not be accessed externally, otherwise it will destroy the results you have encapsulated.
The debug method here cannot be accessed from the outside because it is a private method in the plugin display.
6. Support metadata plugin.
Using Metadata Plugin depends on the type of your plugin. It may make your plugin more powerful. Personally, I prefer the metadata plugin because it allows my plguin options to be overloaded through tags.
If the metadata plugin can be successfully encapsulated into our plugin, you can use this lilight plugin through the following tag.
The final code is as follows: