Home > Article > Web Front-end > Detailed explanation of jQuery’s observer pattern_jquery
In jQuery, the on method can bind events to elements, and the trigger method can manually trigger events. Focusing on these two methods, let's experience the Observer Pattern in jQuery.
■ The on method binds built-in events and triggers them naturally
For example, if we bind a click event to the body element of the page, write like this.
■ The on method binds built-in events and triggers them manually
Using the trigger method, you can also manually trigger the built-in event bound to the element.
In the above, there is no need to click the body. After the page is loaded, the body automatically triggers the click event.
We know that click is a built-in event of jquery. So, can the event be customized and triggered manually?
Above, we customized a someclick event, and the result is the same as above.
So, we found that we can bind a custom event to the element and trigger the event using the trigger method.
Of course, the name of the custom event can be written in the form of "namespace.custom event name", such as app.someclick. This is especially useful in large projects, which can effectively avoid custom event name conflicts.
From the perspective of "publish and subscribe", the on method is equivalent to a subscriber and an observer, and the trigger method is equivalent to a publisher.
■ Experience the jQuery observer mode from "Get json data asynchronously"
In the root directory, there is a data.json file.
{
"one" : "Hello",
"two" : "World"
}
Now, get the json data asynchronously.
If you use a global variable to receive asynchronously obtained json data.
This time, the result we got was undefined. Why is this?
--Because, while the $.getJSON method is still getting data, console.log(data) has been executed, and data does not have data at this time.
How to solve this problem?
Above, the on method is like a subscriber, which subscribes to the custom event app.myevent; and the trigger method is like a publisher, which publishes events and parameters before the subscriber method is actually executed.
■ Extension methods of jQuery observer pattern
For this purpose, we can also write an extension method specifically for the jQuery observer pattern.
The above defines the global publish and subscribe methods, which we can call at any time.