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

Source: Internet
Author: User

An event (or message) is a frequently used software design pattern. Can reduce the coupling between the message processor and the message publisher, such as the JMS specification inside the Java EE. The Observer pattern in design mode (also called the Advertise/subscribe mode). This is the same for JavaScript code. Previously written in the jquery related blog. This article introduces the event handling mechanism and features of jquery specifically, and can be used to refer to the articles in this folder .


jquery event processing is actually using the Publish/subscribe model, including the namespace mechanism it provides, and its own definition of events are very good, but jquery event processing has a flaw: jquery events are related to DOM elements, but very often we do not need DOM elements. Just want to use a mechanism like event advertisement/subscription.

Code Listing 1: Assume that a DOM element does not exist. Then you can't rely on it to use event announcements and subscriptions.

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. The following code will 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 solve the above problems by using the AMPLIFYJS framework in our projects.

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 be executed normally, and can be seen by the way AMPLIFYJS is used. It just makes up for the lack of jquery event handling.


attached below AMP LIFYJS Source code is amplify.core.js. Can see the source code is very short, but also very 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));


More specific API use, you can refer to the following 2 articles:

Brief analysis of source code of AMPLIFYJS: Event distribution

Extending Your jQuery Application with Amplify.js


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

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.