Write better, more elegant JavaScript event handling code using AMPLIFYJS and jquery

Source: Internet
Author: User

An event (or message) is a common software design pattern that reduces the coupling between a message processor and a message publisher, such as the JMS specification inside a Java EE. The Observer pattern in design mode (also called the Publish/Subscribe pattern), which is also true for JavaScript code. In the previous jquery-related blogs, the event handling mechanism and features of jquery are described in detail, and can be found in the articles in this directory .


jquery event processing is actually using the Publish/subscribe model, including the namespace mechanism it provides, custom events are very good, but jquery event processing has a flaw: jquery events are related to DOM elements, but many times we do not need DOM elements, You only want to use the event's publish/subscribe mechanism.

Code Listing 1: If a DOM element does not exist, you cannot rely on it to use the publication and subscription of the event.

Not-exsit does not exist for DOM elements, event handling is invalid $ ("Not-exsit"). Bind ("Self-event", function () {alert (11);}); $ ("Not-exsit"). Trigger ("self-event");

The code 2:jquery does not provide a global bind/trigger, and the following code will give an error.

Report exception $.trigger is not a function  $.bind ("Self-event", function () {alert (one);});  $.trigger ("Self-event");


with the above code 1 and code 2, we can see the shortcomings of the jquery event. We can use the AMPLIFYJS framework in the project to solve the problem above. AMPLIFYJS official website http://amplifyjs.com/and code http://www.bootcdn.cn/amplifyjs/.

<script src= "Amplify.js" ></script><script>amplify.subscribe ("Self-event", function (context) { Console.log ("Priority=5,data=" +json.stringify (context));}, 5); Amplify.subscribe ("Self-event", function (context) { Console.log ("Priority=6,data=" +json.stringify (context));}, 6);   Amplify.subscribe ("Self-event", function (context) {Console.log ("priority=3,data=" +json.stringify (context));}, 3);      Amplify.publish ("Self-event", {data:11});  </script>
This code can run normally, through the use of AMPLIFYJS can be seen, it just makes up for jquery event processing deficiencies.


attached below AMP lifyjs Source code amplify.core.js, you can see the source code is very short, it is easy to read.

/*! * Amplify Core 1.1.2 * * Copyright 2011-2013 appendTo LLC. (http://appendto.com/team) * Dual licensed under the MIT or GPL licenses. * http://appendto.com/open-source-licenses * * http://amplifyjs.com * * (function (global, undefined) {var slice = [].slice , subscriptions = {};var Amplify = Global.amplify = {publish:function (topic) {if (typeof topic!== "string") {throw NE W Error ("You must provide a valid topic to publish."); var args = slice.call (arguments, 1), topicsubscriptions,subscription,length,i = 0,ret;if (!subscriptions[topic]) {RET Urn true;} topicsubscriptions = subscriptions[topic].slice (); for (length = topicsubscriptions.length; i < length; i++) {SUBSCR Iption = topicsubscriptions[I];ret = subscription.callback.apply (Subscription.context, args); if (ret = = = False) {bre AK;}} return ret!== false;},subscribe:function (topic, context, callback, priority) {if (typeof topic!== "string") {throw New Error ("must provide a valid topic to create a suBscription. "); if (arguments.length = = = 3 && typeof callback = = = "Number") {priority = Callback;callback = Context;context = Nu ll;} if (arguments.length = = = 2) {callback = Context;context = null;} Priority = Priority | | 10;var Topicindex = 0,topics = Topic.split (/\s/), topiclength = Topics.length,added;for (; topicindex < topicLength; topicindex++) {topic = topics[topicindex];added = false;if (!subscriptions[topic]) {subscriptions[topic] = [];} var i = subscriptions[topic].length-1,subscriptioninfo = {callback:callback,context:context,priority:priority};for (; I >= 0; i--) {if (subscriptions[topic] [I].priority <= priority) {subscriptions[topic].splice (i + 1, 0, subscriptioninfo); a dded = True;break;}} if (!added) {subscriptions[topic].unshift (Subscriptioninfo);}} return callback;},unsubscribe:function (topic, context, callback) {if (typeof topic!== "string") {throw new Error ("Y OU must provide a valid topic to remove a subscriptiOn. "); if (arguments.length = = = 2) {callback = Context;context = null;} if (!subscriptions[topic]) {return;} var length = subscriptions[Topic].length,i = 0;for (; i < length; i++) {if (subscriptions[topic] [I].callback = = = callback) {if (!context | | subscriptions[topic [I].context = = context) {subscriptions[topic].splice (I, 1); /Adjust counter and length for removed itemi--;length--;}}}};} (this));


For more detailed API usage, refer to the following 2 articles:

Brief analysis of AMPLIFYJS source code: Event Distribution

Extending Your jQuery Application with Amplify.js


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Write better, more elegant JavaScript event handling code using AMPLIFYJS and jquery

Related Article

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.