jquery Viewer model in detail reproduced

Source: Internet
Author: User

An explanation of the observer pattern of jquery

Submitted by: Hebedich

This article mainly introduces the on method and the trigger method in jquery, and the observer pattern which is experienced around this method, is a very good article, it is very helpful for us to understand the observer pattern.

Undefined

Undefined

On method binding built-in events, naturally triggering

For example, we bind a click event to the BODY element of the page, so write.

Above, we can only click on the body to trigger the Click event. That is, when a built-in event is bound to a page element, the event is triggered at the moment the built-in event occurs.

On method binding built-in events, manually triggering

You can also manually trigger a built-in event for element binding using the Trigger method.

<script src= "Scripts/jquery-2.1.1.min.js" ></script> <script type= "Text/javascript" > $ (functi             On () {$ (' body '). On (' click ', Function () {Console.log (' was clicked ~ ~ ');             });         $ (' body '). Trigger (' click ');          }); </script> above, no need to click on the body, after the page loaded, the body automatically triggered the Click event.

The on method binds the custom event, which is triggered manually

We know that Click is a jquery built-in event, so can you customize the event and trigger it manually?

<script src= "Scripts/jquery-2.1.1.min.js" ></script> <script type= "Text/javascript" > $ (functi             On () {$ (' body '). On (' Someclick ', function () {Console.log (' was clicked ~ ~ ');             });         $ (' body '). Trigger (' Someclick ');          }); </script>

Above, we customize a Someclick event and get the same result as above.

As a result, we found that we can bind custom events for elements and trigger the event with 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, which is especially useful in large projects, which effectively avoids custom event name collisions.

If you look at the "Publish subscription" perspective, the on method equals the subscriber, the Observer, and the trigger method is the publisher.

Experience the jquery Observer pattern from "get JSON data asynchronously"

In the root directory, there is a Data.json file.

{"One": "Hello", "One", "World"} Now, get the JSON data asynchronously.

<script src= "Scripts/jquery-2.1.1.min.js" ></script> <script type= "Text/javascript" > $ (functi             On () {$.getjson (' Data.json ', function (data) {Console.log (data);         });          }); </script>

If a global variable is used to receive the JSON data obtained asynchronously.

<script src= "Scripts/jquery-2.1.1.min.js" ></script> <script type= "Text/javascript" > $ (functi             On () {var data;             $.getjson (' Data.json ', function (results) {data = results;             });         Console.log (data);          }); </script>

This time, we get the result is undefined, this is why? -Because when the $.getjson method is still fetching data, Console.log (data) is already executing, and data does not yet.

How to solve this problem? -If you define a method that needs to be executed outside of the $.getjson method, and then actually trigger the method in the callback function of the $.getjson method, does it solve the problem?

<script src= "Scripts/jquery-2.1.1.min.js" ></script> <script type= "Text/javascript" > $ (functi On () {$.getjson (' Data.json ', function (results) {$ (document). Trigger (' app.myevent ', results) ;             Equivalent to publish});             $ (document). On (' App.myevent ', function (e, results) {//= subscription Console.log (results);         });          }); </script>

Above, the on method is like a subscriber, it subscribes to custom event app.myevent, and the trigger method is like a publisher, which publishes events and parameters before really letting the Subscriber method execute.

The extension method of jquery Observer pattern

To do this, we can also write an extension method specifically for the jquery Observer pattern.

    <script src= "scripts/jquery-2.1.1.min.js" ></script>     <script Type= "Text/javascript" >         $ (function () {             $.getjson (' Data.json ', function (results) {                 $.publish (' app.myevent ', results);            });             $.subscribe (' app.myevent ', function (E, results ) {                Console.log ( Results);            });        });         (function ($) {             var o = $ ({});//Custom ThingsItem Objects             $.each ({                 Trigger: ' Publish ',                  on: ' Subscribe ',                  off: ' Unsubscribe '             }, function (key, Val) {                 Jquery[val] = function () {                     o[key].apply (o, arguments);                };            });        }) (JQuery);    </script>

Above, we define the global publish and subscribe methods, which we can call at any time.

    <script src= "scripts/jquery-2.1.1.min.js" ></script>     <script Type= "Text/javascript" >         $ (function () {             $.getjson (' Data.json ', function (results) {                 $.publish (' app.myevent ', results);            });             $.subscribe (' app.myevent ', function (E, results ) {                $ (' body '). HTML (                      Results.one                );            });        });


Quote this

/** *   (function($     ) {var o = $ ({}      ); function () {      o.on.apply (o, arguments);    };       function () {      o.off.apply (o, arguments);    };      function () {      o.trigger.apply (o, arguments);    };   

JQuery Viewer Mode in a detailed reprint

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: info-contact@alibabacloud.com 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.