第三參數 | 對應事件 | 效果 | 取消事件 |
---|---|---|---|
true | 事件捕捉 | 從外向內傳播 | |
false | 事件冒泡 | 從內向外傳播 | e.stopPropagation() |
e.preventDefault() / return false
list.addEventListener("click", function(e) { if(e.currentTarget.tagName == "LI") { /**/ } }, false)
以jquery插件爲例;下面代碼使用自定義事件讓代碼變得整潔,在點擊選項卡時觸發一個change.tabs事件,並綁定若干回調方法來修改active類html
<ul id="tabs"> <li data-tab="user">Users</li> <li data-tab="group">Groups</li> </ul> <div id="tabsContent"> <div data-tab="user">user</div> <div data-tab="group">group</div> </div>
jQuery.fn.tabs = function(control) { var elem = $(this); control = $(control); elem.on("click", "li", function() { var tabName = $(this).attr("data-tab"); elem.trigger("change.tabs", tabName); }); elem.on("change.tabs", function(e, tabName) { elem.find("li").removeClass("active"); elem.find(">[data-tab='" + tabName + "']").addClass("active"); }); elem.on("change.tabs", function(e, tabName) { control.find(">[data-tab]").removeClass("active"); control.find(">[data-tab='" + tabName + "']").addClass("active"); }); //將切換選項卡的動做和窗口的hash作關聯,這樣能夠使用瀏覽器的退後按鈕 elem.on("change.tabs", function(e, tabName) { window.location.hash = tabName; }); $(window).on("hashchange", function() { var tabName = window.location.hash.slice(1); elem.trigger("change.tabs", tabName); }) var firstName = elem.find("li:first").attr("data-tab"); elem.trigger("change.tabs", firstName); return this; } $("ul#tabs").tabs("#tabsContent");
var PubSub = { //訂閱 subscribe: function(ev, callbacks) { //雙重賦值 var calls = this._callbacks || (this._callbacks = {}); (this._callbacks[ev] || (this._callbacks[ev] = [])).push(callbacks); return this; }, //發佈 publish: function() { var args = Array.prototype.slice.call(arguments, 0); var ev = args.shift(); var list, calls, i, l; if(!(calls = this._callbacks)) return this; if(!(list = this._callbacks[ev])) return this; for(i = 0, l = list.length; i < l; i++) list[i].apply(this, args); return this; } } PubSub.subscribe("wem", function() {}); PubSub.publish("wem"); //能夠使用命名空間的方式管理事件名稱 PubSub.subscribe("user:create", function() {});
將其擴充到一個局部對象jquery
var Asset = {}; jQuery.extend(Asset, PubSub); Asset.subscribe("test", function() {alert("test")}); Asset.publish("test");
使用jquery實現該模式編程
(function($) { var o = $({}); $.subscribe = function() { o.bind.apply(o, arguments); }; $.unsubscribe = function() { o.unbind.apply(o, arguments); }; $.publish = function() { var arguments = $.makeArray(arguments); var type = arguments[0]; arguments.shift(); o.trigger.apply(o, [type, arguments]); } })(jQuery); $.subscribe("/some/topic", function(event, a, b, c) { console.log(event.type, a + b +c); }); $.publish("/some/topic","a","b","c");