加载中...

观察者模式


观察者模式

另一个我们之前提到过的模式就是观察者(发布/订阅)模式.这种模式下,系统中的对象可以在关注的事件发生的时候给其他对象发送消息,也可以被其他对象所通知。

jQuery核心库很多年前就已经提供了对于类似于发布/订阅系统的支持,它们称之为定制事件。

jQuery的早期版本中,可以通过使用jQuery.bind()(订阅),jQuery.trigger()(发布),和jQuery.unbind()(取消订阅)来使用这些定制事件,但在近期的版本中,这些都可以通过使用jQuery.on(),jQuery.trigger()和jQuery.off()来完成。

下面我们来看一下实际应用中的一个例子:

  1. // Equivalent to subscribe(topicName, callback)
  2. $( document ).on( "topicName" , function () {
  3. //..perform some behaviour
  4. });
  5. // Equivalent to publish(topicName)
  6. $( document ).trigger( "topicName" );
  7. // Equivalent to unsubscribe(topicName)
  8. $( document ).off( "topicName" );

对于jQuery.on()和jQuery.off()的调用最后会经过jQuery的事件系统,与Ajax一样,由于它们的实现代码相对较长,我们只看一下实际上事件处理器是在哪儿以及如何将定制事件加入到系统中的:

  1. jQuery.event = {
  2. add: function( elem, types, handler, data, selector ) {
  3. var elemData, eventHandle, events,
  4. t, tns, type, namespaces, handleObj,
  5. handleObjIn, quick, handlers, special;
  6. ...
  7. // Init the element's event structure and main handler,
  8. //if this is the first
  9. events = elemData.events;
  10. if ( !events ) {
  11. elemData.events = events = {};
  12. }
  13. ...
  14. // Handle multiple events separated by a space
  15. // jQuery(...).bind("mouseover mouseout", fn);
  16. types = jQuery.trim( hoverHack(types) ).split( " " );
  17. for ( t = 0; t < types.length; t++ ) {
  18. ...
  19. // Init the event handler queue if we're the first
  20. handlers = events[ type ];
  21. if ( !handlers ) {
  22. handlers = events[ type ] = [];
  23. handlers.delegateCount = 0;
  24. // Only use addEventListener/attachEvent if the special
  25. // events handler returns false
  26. if ( !special.setup || special.setup.call( elem, data,
  27. //namespaces, eventHandle ) === false ) {
  28. // Bind the global event handler to the element
  29. if ( elem.addEventListener ) {
  30. elem.addEventListener( type, eventHandle, false );
  31. } else if ( elem.attachEvent ) {
  32. elem.attachEvent( "on" + type, eventHandle );
  33. }
  34. }
  35. }

对于那些喜欢使用传统的命名方案的人, Ben Alamn对于上面的方法提供了一个简单的包装,然后为我们提供了jQuery.publish(),jQuery.subscribe和jQuery.unscribe方法。我之前在书中提到过,现在我们可以完整的看一下这个包装器。

  1. (function( $ ) {
  2. var o = $({});
  3. $.subscribe = function() {
  4. o.on.apply(o, arguments);
  5. };
  6. $.unsubscribe = function() {
  7. o.off.apply(o, arguments);
  8. };
  9. $.publish = function() {
  10. o.trigger.apply(o, arguments);
  11. };
  12. }( jQuery ));

在近期的jQuery版本中,一个多目的的回调对象(jQuery.Callbacks)被提供用来让用户在回调列表的基础上写新的方案。另一个发布/订阅系统就是一个使用这个特性写的方案,它的实现方式如下:

  1. var topics = {};
  2. jQuery.Topic = function( id ) {
  3. var callbacks,
  4. topic = id && topics[ id ];
  5. if ( !topic ) {
  6. callbacks = jQuery.Callbacks();
  7. topic = {
  8. publish: callbacks.fire,
  9. subscribe: callbacks.add,
  10. unsubscribe: callbacks.remove
  11. };
  12. if ( id ) {
  13. topics[ id ] = topic;
  14. }
  15. }
  16. return topic;
  17. };

然后可以像下面一样使用:

  1. // Subscribers
  2. $.Topic( "mailArrived" ).subscribe( fn1 );
  3. $.Topic( "mailArrived" ).subscribe( fn2 );
  4. $.Topic( "mailSent" ).subscribe( fn1 );
  5. // Publisher
  6. $.Topic( "mailArrived" ).publish( "hello world!" );
  7. $.Topic( "mailSent" ).publish( "woo! mail!" );
  8. // Here, "hello world!" gets pushed to fn1 and fn2
  9. // when the "mailArrived" notification is published
  10. // with "woo! mail!" also being pushed to fn1 when
  11. // the "mailSent" notification is published.
  12. // Outputs:
  13. // hello world!
  14. // fn2 says: hello world!
  15. // woo! mail!

还没有评论.