国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

詳解JavaScript中的自定義事件編寫

2019-11-20 10:06:55
字體:
來源:轉載
供稿:網友

我們可以自定義事件來實現更靈活的開發,事件用好了可以是一件很強大的工具,基于事件的開發有很多優勢(后面介紹)。

與自定義事件的函數有 Event、CustomEvent 和 dispatchEvent。

直接自定義事件,使用 Event 構造函數:

var event = new Event('build');// Listen for the event.elem.addEventListener('build', function (e) { ... }, false);// Dispatch the event.elem.dispatchEvent(event);

CustomEvent 可以創建一個更高度自定義事件,還可以附帶一些數據,具體用法如下:

var myEvent = new CustomEvent(eventname, options);

其中 options 可以是:

{  detail: {    ...  },  bubbles: true,  cancelable: false}

其中 detail 可以存放一些初始化的信息,可以在觸發的時候調用。其他屬性就是定義該事件是否具有冒泡等等功能。

內置的事件會由瀏覽器根據某些操作進行觸發,自定義的事件就需要人工觸發。dispatchEvent 函數就是用來觸發某個事件:

element.dispatchEvent(customEvent);

上面代碼表示,在 element 上面觸發 customEvent 這個事件。結合起來用就是:

// add an appropriate event listenerobj.addEventListener("cat", function(e) { process(e.detail) });// create and dispatch the eventvar event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});obj.dispatchEvent(event);

使用自定義事件需要注意兼容性問題,而使用 jQuery 就簡單多了:

// 綁定自定義事件$(element).on('myCustomEvent', function(){});// 觸發事件$(element).trigger('myCustomEvent');此外,你還可以在觸發自定義事件時傳遞更多參數信息:$( "p" ).on( "myCustomEvent", function( event, myName ) { $( this ).text( myName + ", hi there!" );});$( "button" ).click(function () { $( "p" ).trigger( "myCustomEvent", [ "John" ] );});

JavaScript 自定義事件就是有別于如 click, submit 等標準事件的自行定制的事件,在敘述自定義事件有何好處之前,先來看一個自定義事件的例子:

<div id="testBox"></div>// 創建事件var evt = document.createEvent('Event');// 定義事件類型evt.initEvent('customEvent', true, true);// 在元素上監聽事件var obj = document.getElementById('testBox');obj.addEventListener('customEvent', function(){  console.log('customEvent 事件觸發了');}, false);

具體效果可以查看 Demo,在 console 中輸入 obj.dispatchEvent(evt),可以看到 console 中輸出“customEvent 事件觸發了”,表示自定義事件成功觸發。

在這個過程中,createEvent 方法創建了一個空事件 evt,然后使用 initEvent 方法定義事件的類型為約定好的自定義事件,再對相應的元素進行監聽,接著,就是使用 dispatchEvent 觸發事件了。

沒錯,自定義事件的機制如普通事件一樣――監聽事件,寫回調操作,觸發事件后執行回調。但不同的是,自定義事件完全由我們控制觸發時機,這就意味著實現了一種 JavaScript 的解耦。我們可以把多個關聯但邏輯復雜的操作利用自定義事件的機制靈活地控制好。

當然,可能你已經猜到了,上面的代碼在低版本的 IE 中并不生效,事實上在 IE8 及以下版本的 IE 中并不支持 createEvent(),而有 IE 私有的 fireEvent() 方法,但遺憾的是,fireEvent 只支持標準事件的觸發。因此,我們只能使用一個特殊而簡單的方法觸發自定義事件。

// type 為自定義事件,如 type = 'customEvent',callback 為開發者實際定義的回調函數obj[type] = 0;obj[type]++; obj.attachEvent('onpropertychange', function(event){  if( event.propertyName == type ){    callback.call(obj);  }});

這個方法的原理實際上是在 DOM 中增加一個自定義屬性,同時監聽元素的 propertychange 事件,當 DOM 的某個屬性的值發生改變時就會觸發 propertychange 的回調,再在回調中判斷發生改變的屬性是否為我們的自定義屬性,若是則執行開發者實際定義的回調。從而模擬了自定義事件的機制。

為了使到自定義事件的機制能配合標準事件的監聽和模擬觸發,這里給出一個完整的事件機制,這個機制支持標準事件和自定義事件的監聽,移除監聽和模擬觸發操作。需要注意的是,為了使到代碼的邏輯更加清晰,這里約定自定義事件帶有 'custom' 的前綴(例如:customTest,customAlert)。

/** * @description 包含事件監聽、移除和模擬事件觸發的事件機制,支持鏈式調用 * */ (function( window, undefined ){ var Ev = window.Ev = window.$ = function(element){   return new Ev.fn.init(element);}; // Ev 對象構建 Ev.fn = Ev.prototype = {   init: function(element){     this.element = (element && element.nodeType == 1)? element: document;  },   /**   * 添加事件監聽   *    * @param {String} type 監聽的事件類型   * @param {Function} callback 回調函數   */   add: function(type, callback){     var _that = this;         if(_that.element.addEventListener){             /**       * @supported For Modern Browers and IE9+       */             _that.element.addEventListener(type, callback, false);           } else if(_that.element.attachEvent){             /**       * @supported For IE5+       */       // 自定義事件處理      if( type.indexOf('custom') != -1 ){         if( isNaN( _that.element[type] ) ){           _that.element[type] = 0;         }          var fnEv = function(event){           event = event ? event : window.event                     if( event.propertyName == type ){            callback.call(_that.element);          }        };         _that.element.attachEvent('onpropertychange', fnEv);         // 在元素上存儲綁定的 propertychange 的回調,方便移除事件綁定        if( !_that.element['callback' + callback] ){               _that.element['callback' + callback] = fnEv;         }          // 標準事件處理      } else {            _that.element.attachEvent('on' + type, callback);      }           } else {             /**       * @supported For Others       */             _that.element['on' + type] = callback;     }     return _that;  },   /**   * 移除事件監聽   *    * @param {String} type 監聽的事件類型   * @param {Function} callback 回調函數   */     remove: function(type, callback){     var _that = this;         if(_that.element.removeEventListener){             /**       * @supported For Modern Browers and IE9+       */             _that.element.removeEventListener(type, callback, false);           } else if(_that.element.detachEvent){             /**       * @supported For IE5+       */             // 自定義事件處理      if( type.indexOf('custom') != -1 ){         // 移除對相應的自定義屬性的監聽        _that.element.detachEvent('onpropertychange', _that.element['callback' + callback]);         // 刪除儲存在 DOM 上的自定義事件的回調        _that.element['callback' + callback] = null;            // 標準事件的處理      } else {              _that.element.detachEvent('on' + type, callback);            }     } else {             /**       * @supported For Others       */             _that.element['on' + type] = null;           }     return _that;   },     /**   * 模擬觸發事件   * @param {String} type 模擬觸發事件的事件類型   * @return {Object} 返回當前的 Kjs 對象   */     trigger: function(type){     var _that = this;         try {        // 現代瀏覽器      if(_that.element.dispatchEvent){        // 創建事件        var evt = document.createEvent('Event');        // 定義事件的類型        evt.initEvent(type, true, true);        // 觸發事件        _that.element.dispatchEvent(evt);      // IE      } else if(_that.element.fireEvent){                 if( type.indexOf('custom') != -1 ){           _that.element[type]++;         } else {           _that.element.fireEvent('on' + type);        }          }     } catch(e){     };     return _that;         }} Ev.fn.init.prototype = Ev.fn; })( window );測試用例1(自定義事件測試)// 測試用例1(自定義事件測試)// 引入事件機制// ...// 捕捉 DOMvar testBox = document.getElementById('testbox');// 回調函數1function triggerEvent(){    console.log('觸發了一次自定義事件 customConsole');}// 回調函數2function triggerAgain(){    console.log('再一次觸發了自定義事件 customConsole');}// 封裝testBox = $(testBox);// 同時綁定兩個回調函數,支持鏈式調用testBox.add('customConsole', triggerEvent).add('customConsole', triggerAgain);

完整的代碼在 Demo

打開 Demo 后,在 console 中調用 testBox.trigger('customConsole') 自行觸發自定義事件,可以看到 console 輸出兩個提示語,再輸入 testBox.remove('customConsole', triggerAgain) 移除對后一個監聽,這時再使用 testBox.trigger('customConsole') 觸發自定義事件,可以看到 console 只輸出一個提示語,即成功移除后一個監聽,至此事件機制所有功能正常工作。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浪卡子县| 萍乡市| 开阳县| 西充县| 华容县| 乃东县| 安丘市| 通辽市| 鸡东县| 钟山县| 永昌县| 同心县| 墨玉县| 镇康县| 连南| 大化| 铅山县| 视频| 晋宁县| 田林县| 大姚县| 分宜县| 丹寨县| 邹平县| 静乐县| 阳西县| 哈巴河县| 潜江市| 伊川县| 化州市| 郴州市| 德化县| 鄂州市| 新丰县| 娄底市| 伊川县| 华蓥市| 青海省| 江华| 东丰县| 东丰县|