The role of event distribution
When adding various interactive functions to the page, the simplest way we are familiar with is to bind events to the page elements, and then do the actions we want to do in the event handling function. Code like this:
element.onclick = function(event){ // Do anything. };
If the action we want to do is not complicated, then the code of the actual logical function can be placed here. If you need to modify it in the future, go to the location of this event handling function to modify it.
Furthermore, in order to achieve proper code reuse, we may split part of the logic function into a function:
element.onclick = function(event){ // Other code here. doSomethingElse(); };
The function corresponding to the function doSomethingElse here may be used in other places, so it will be split like this. In addition, there may be a function such as setting coordinates (assuming the function is called setPosition), and you also need to use information such as pointer position provided by the browser event object event:
element.onclick = function(event){ // Other code here. doSomethingElse(); setPosition(event.clientX, event.clientY); };
A not recommended approach here is to pass the event object directly to setPosition. This is because it is a good practice to separate the responsibilities of logical functions and event listening. Only letting the event processing function itself access the browser event object helps reduce code coupling and facilitates independent testing and maintenance.
So, what will happen if the functions become more and more complex? If you follow the previous approach, it might look like this:
element.onclick = function(event){ doMission1(); doMission2(event.clientX, event.clientY); doMission3(); // ... doMissionXX(); };
Although it is okay to use it this way, in this case you can actually consider a more elegant way of writing:
element.onclick = function(event){ amplify.publish( "aya:clicked", { x: event.clientX, y: event.clientY }); };
This form is event distribution. Please note that the events here do not refer to browser native events (event objects), but custom events at the logical level. The aya:clicked above is a custom event name written casually (really?).
Obviously this is not the end yet. In order to complete the previous complex functions, we still need to associate custom events with the things to be done:
amplify.subscribe( "aya:clicked", doMission1); // ... amplify.subscribe( "aya:clicked", doMission2); // ...
Looks like it’s come around again? True, but it works. On the one hand, the listening of browser native events has been separated and solidified. If the logical functions change in the future, for example, several functions are reduced, you only need to delete the associated code part of the custom event, and there is no need to worry about it anymore. Native events. On the other hand, the adjustment of logical functions has become more flexible. Functions can be added through subscribe at any code location, and classification management (customized event names) can be done by oneself.
To put it simply, event distribution reduces the coupling between code modules by adding a layer of redundancy of custom events (when there are only simple logic functions, you will think it is redundant), making the logic The functions are clearer and organized, making subsequent maintenance easier.
Wait a minute, what does that famous amplify in front of me who has traveled abroad several times do?
Nice, it’s finally time to introduce this.
AmplifyJS
Event distribution requires certain methods to be implemented. One of the design patterns for event distribution is Publish/Subscribe.
AmplifyJS is a simple JavaScript library that mainly provides three functions: Ajax request, data storage, and publish/subscribe (each of which can be used independently). Among them, publish/subscribe is the core function, and the corresponding name is amplify.core.
amplify.core is a concise and clear implementation of the publish/subscribe design pattern, with more than 100 lines in total including comments. After reading amplify's source code, you can better understand how to implement a publish/subscribe design pattern.
Overview of the code
The overall structure of the source code of amplify.core is as follows:
(function( global, undefined ) { var slice = [].slice, subscriptions = {}; var amplify = global.amplify = { publish: function( topic ) { // ... }, subscribe: function( topic, context, callback, priority ) { // ... }, unsubscribe: function( topic, context, callback ) { // ... } }; }( this ) );
As you can see, amplify defines a global variable named amplify (as an attribute of global), which has three methods publish, subscribe, and unsubscribe. In addition, subscriptions serves as a local variable that will save all custom event names and associated functions involved in the publish/subscribe mode.
publish
publish is published. It requires specifying a topic, which is a custom event name (or just called a topic). After calling, all functions associated with a certain topic will be called in sequence:
publish: function( topic ) { // [1] if ( typeof topic !== "string" ) { throw new Error( "You must provide a valid topic to publish." ); } // [2] var args = slice.call( arguments, 1 ), topicSubscriptions, subscription, length, i = 0, ret; if ( !subscriptions[ topic ] ) { return true; } // [3] topicSubscriptions = subscriptions[ topic ].slice(); for ( length = topicSubscriptions.length; i < length; i++ ) { subscription = topicSubscriptions[ i ]; ret = subscription.callback.apply( subscription.context, args ); if ( ret === false ) { break; } } return ret !== false; },
[1],参数topic必须要求是字符串,否则抛出一个错误。
[2],args将取得除topic之外的其他所有传递给publish函数的参数,并以数组形式保存。如果对应topic在subscriptions中没有找到,则直接返回。
[3],topicSubscriptions作为一个数组,取得某一个topic下的所有关联元素,其中每一个元素都包括callback及context两部分。然后,遍历元素,调用每一个关联元素的callback,同时带入元素的context和前面的额外参数args。如果任意一个关联元素的回调函数返回false,则停止运行其他的并返回false。
subscribe
订阅,如这个词自己的含义那样(就像订本杂志什么的),是建立topic和callback的关联的步骤。比较特别的是,amplify在这里还加入了priority(优先级)的概念,优先级的值越小,优先级越高,默认是10。优先级高的callback,将会在publish的时候,被先调用。这个顺序的原理可以从前面的publish的源码中看到,其实就是预先按照优先级从高到低依次排列好了某一topic的所有关联元素。
subscribe: function( topic, context, callback, priority ) { if ( typeof topic !== "string" ) { throw new Error( "You must provide a valid topic to create a subscription." ); } // [1] if ( arguments.length === 3 && typeof callback === "number" ) { priority = callback; callback = context; context = null; } if ( arguments.length === 2 ) { callback = context; context = null; } priority = priority || 10; // [2] 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 ] = []; } // [3] var i = subscriptions[ topic ].length - 1, subscriptionInfo = { callback: callback, context: context, priority: priority }; // [4] for ( ; i >= 0; i-- ) { if ( subscriptions[ topic ][ i ].priority <= priority ) { subscriptions[ topic ].splice( i + 1, 0, subscriptionInfo ); added = true; break; } } // [5] if ( !added ) { subscriptions[ topic ].unshift( subscriptionInfo ); } } return callback; },
[1],要理解这一部分,请看amplify提供的API示意:
amplify.subscribe( string topic, function callback ) amplify.subscribe( string topic, object context, function callback ) amplify.subscribe( string topic, function callback, number priority ) amplify.subscribe( string topic, object context, function callback, number priority )
可以看到,amplify允许多种参数形式,而当参数数目和类型不同的时候,位于特定位置的参数可能会被当做不同的内容。这也在其他很多JavaScript库中可以见到。像这样,通过参数数目和类型的判断,就可以做到这种多参数形式的设计。
[2],订阅的时候,topic是允许空格的,空白符将被当做分隔符,认为是将一个callback关联到多个topic上,所以会使用一个循环。added用作标识符,表明新加入的这个元素是否已经添加到数组内,初始为false。
[3],每一个callback的保存,实际是一个对象,除callback外还带上了context(默认为null)和priority。
[4],这个循环是在根据priority的值,找到关联元素应处的位置。任何topic的关联元素都是从无到有,且依照priority数值从小到大排列(已排序的)。因此,在比较的时候,是先假设新加入的元素的priority数值较大(优先级低),从数组尾端向前比较,只要原数组中有关联元素的priority数值比新加入元素的小,循环就可以中断,且可以确定地用数组的splice方法将新加入的元素添加在此。如果循环一直运行到完毕,则可以确定新加入的元素的priority数值是最小的,此时added将保持为初始值false。
[5],如果到这个位置,元素还没有被添加,那么执行添加,切可以确定元素应该位于数组的最前面(或者是第一个元素)。
unsubscribe
虽然发布和订阅是最主要的,但也会有需要退订的时候(杂志不想看了果断退!)。所以,还会需要一个unsubscribe。
unsubscribe: function( topic, context, callback ) { if ( typeof topic !== "string" ) { throw new Error( "You 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 item i--; length--; } } } }
读过前面的源码后,这部分看起来就很容易理解了。根据指定的topic遍历关联元素,找到callback一致的,然后删除它。由于使用的是splice方法,会直接修改原始数组,因此需要手工对i和length再做一次调整。
Amplify使用示例
官方提供的其中一个使用示例是:
amplify.subscribe( "dataexample", function( data ) { alert( data.foo ); // bar }); //... amplify.publish( "dataexample", { foo: "bar" } );
结合前面的源码部分,是否对发布/订阅这一设计模式有了更明确的体会呢?
补充说明
你可能也注意到了,AmplifyJS所实现的典型的发布/订阅是同步的(synchronous)。也就是说,在运行amplify.publish(topic)的时候,是会没有任何延迟地把某一个topic附带的所有回调,全部都运行一遍。
结语
Pub/Sub是一个比较容易理解的设计模式,但非常有用,可以应对大型应用的复杂逻辑。本文简析的AmplifyJS是我觉得写得比较有章法而且简明切题(针对单一功能)的JavaScript库,所以在此分享给大家。