jQuery 实现观察者模式

github:

https://github.com/mmikowski/jquery.event.gevent

demo:

$('body').append( "<div id='spa-chat-list-box' />" );

var $listbox = $('#spa-chat-list-box');

$listbox.css({
    position   : "absolute",
    'z-index'  : "3",
    top        : "50",
    left       : "50",
    width      : "50",
    height     : "50",
    border     : "2px solid #ccc",
    background : "#fff",
})

var onListchange = function ( event, update_map ){
    $( this ).html(update_map.list_text);
    alert("onListchange");
}

/* 订阅事件 */
$.gevent.subscribe(
    $listbox,
    'spa-listchange',
    onListchange
);

/* 发布通知 */
$.gevent.publish(
    'spa-listchange',
    [{  list_text : 'the list is here'}]
);

/* 删除元素的话,订阅的事件也会删除 */
$listbox.remove();
$.gevent.publish('spa-listchange',[ { } ]);
原文地址:https://www.cnblogs.com/CyLee/p/6411042.html