私は多目的ファクトリーイベントエミッターファクトリー関数を作成しました。それを使ってオブジェクトをイベントエミッタにすることができます。誰かが見たり使いたい場合は、イベントエミッターファクトリーのコードは以下のとおりです。すべてのDOMイベントの配列を取得する
私の質問は、DOMからイベントのリストを取得する方法です。 私はバインドされたイベントのリストを取得しようとしていません。私は可能なすべての出来事のリストが欲しいです。エミッタに「パイプ」メソッドを追加したいと思います。このメソッドは、DOMオブジェクトを取り、すべての可能なイベントにバインドし、それらのイベントのいずれかが起動すると、それぞれがエミッタ内の同じ名前のイベントをトリガします。
これを行う方法はありません。ハードコードされたイベント名の配列を作成する準備ができていますが、代わりにDOMの配列を取得できれば、W3Cがより多くのイベントタイプを標準化していれば、それははるかに優れています。
P.S.あなたがW3Cのために働くならば、これはみんながDOMを嫌うようなものです。おもしろい言葉のようにJavaScriptをやめてください。おもちゃの言語ではなく、おもちゃのDOM以上のものが必要です。
/**
* Creates a event emitter
*/
function EventEmitter() {
var api, callbacks;
//vars
api = {
"on": on,
"trigger": trigger
};
callbacks = {};
//return the api
return api;
/**
* Binds functions to events
* @param event
* @param callback
*/
function on(event, callback) {
var api;
if(typeof event !== 'string') { throw new Error('Cannot bind to event emitter. The passed event is not a string.'); }
if(typeof callback !== 'function') { throw new Error('Cannot bind to event emitter. The passed callback is not a function.'); }
//return the api
api = {
"clear": clear
};
//create the event namespace if it doesn't exist
if(!callbacks[event]) { callbacks[event] = []; }
//save the callback
callbacks[event].push(callback);
//return the api
return api;
function clear() {
var i;
if(callbacks[event]) {
i = callbacks[event].indexOf(callback);
callbacks[event].splice(i, 1);
if(callbacks[event].length < 1) {
delete callbacks[event];
}
return true;
}
return false;
}
}
/**
* Triggers a given event and optionally passes its handlers all additional parameters
* @param event
*/
function trigger(event ) {
var args;
if(typeof event !== 'string' && !Array.isArray(event)) { throw new Error('Cannot bind to event emitter. The passed event is not a string or an array.'); }
//get the arguments
args = Array.prototype.slice.apply(arguments).splice(1);
//handle event arrays
if(Array.isArray(event)) {
//for each event in the event array self invoke passing the arguments array
event.forEach(function(event) {
//add the event name to the begining of the arguments array
args.unshift(event);
//trigger the event
trigger.apply(this, args);
//shift off the event name
args.shift();
});
return;
}
//if the event has callbacks then execute them
if(callbacks[event]) {
//fire the callbacks
callbacks[event].forEach(function(callback) { callback.apply(this, args); });
}
}
}
私は同様の質問をしました。[ブラウザでページ上のすべてのイベントをプログラムで捕捉することはできますか?](http://stackoverflow.com/questions/5107232/is-it-possible-to-programmatically -catch-all-events-the-the-browser-in-the-browser)を使用します。 –