将事件附加到object / array

时间:2016-05-17 23:17:10

标签: javascript jquery

让我们为你举例说明你有这个数组

 //Defined at the top of your class
 myArray = [];
 //Then somewhere else in the code
 myArray["unique_id"] = {example: true, example2: false, etc..};
 //somewhere else
 delete myArray["unique_id"];

是否有可能有这样的事情:

//when adding
myArray["unique_id"] = {example: true, example2: false, etc..};
myArray.trigger("array:update");
//when deleting
delete myArray["unique_id"];
myArray.trigger("array:delete");

//and in a different file or somewhere else down the path
myArray.on("array:update", function(){
   //do stuff
});

//and in a different file or somewhere else down the path
myArray.on("array:delete", function(){
   //do stuff
});

我喜欢自定义事件系统,我想知道这是否可能。没有找到关于此特定应用程序文档的示例。 基本上将自定义事件附加到数组/对象,而不一定是dom元素。

1 个答案:

答案 0 :(得分:2)

使用Proxy可以做到这一点,但您必须先让对象模拟EventEmitter



//Defined at the top of your class
let myObject = {};

//Emulate EventEmitter
myObject._events = {};
myObject.emit = function emit(event, ...args) {
  (this._events[event] || []).forEach(callback => {
    callback.apply(this, args);
  });
};
myObject.on = function on(event, callback) {
  if (!this._events[event]) {
    this._events[event] = [];
  }

  this._events[event].push(callback);
};

//Define Proxy
let myProxy = new Proxy(myObject, {
  set(target, name, value) {
    target.emit('update', name, value);
    return (target[name] = value);
  },
  deleteProperty(target, name) {
    target.emit('delete', name);
    return (delete target[name]);
  }
});

//and in a different file or somewhere else down the path
myObject.on('update', function(name, value) {
  console.log('update', this, name, value);
});

//and in a different file or somewhere else down the path
myObject.on('delete', function(name) {
  console.log('delete', this, name);
});

//Then somewhere else in the code
myProxy["unique_id"] = {
  example: true,
  example2: false
};
//somewhere else
delete myProxy["unique_id"];