1

我知道你可以创建一个CustomEvent这样的:

var wordCreated = new CustomEvent(
    "newWord", 
    {
        detail: {
            word: "hola",
            translation: "hi",
        },
        bubbles: true,
        cancelable: true
    }
);

我想知道如何在不使用new,Object.create模式的情况下做到这一点?

我没有看到解决方案的问题是它CustomEvent需要两个参数:一个指定事件名称的字符串,以及一个包含bubblescancelabledetails属性的配置对象。我不确定如何将字符串和对象都传递给Object.create.

最终,我希望能够以以下标准方式使用此自定义事件:

var p = document.querySelector('p'); // a random node
p.addEventListener('newWord', function(ev){ console.log(ev) });
p.dispatchEvent(wordCreated);
4

2 回答 2

2

标题中问题的答案“是否可以使用 Object.create 模式来创建 CustomEvent 对象?” 。现在,回答后续问题“你会那样做吗?” 可能是否正如@MartinErnst 指出的那样,您最终将重新发明new已经在做的事情。

(如果你还不知道的话)之间的主要区别在于newObject.createObject.create它创建了一个Object(注意大写的O),它继承了指定为 的第一个参数的对象的原型Object.createnew在返回指定对象的实例之前,操作符在调用给定对象的构造函数的附加步骤中执行相同的操作(注意小写字母o

所以我们可以使用这样的东西Object.create来创建一个Object继承自CustomEvent原型的which:

var customEvent1 = Object.create(CustomEvent, {  
                     detail: {
                        writable:true, 
                        configurable:true, 
                        value: { word:"hola", translation:"hi" }
                      },
                      bubbles: {
                        writable:true,  
                        configurable:true, 
                        value:true 
                      },
                      cancelable:  {
                        writable:true,  
                        configurable:true, 
                        value:true 
                      },
                      type: {
                        writable:true,
                        configurable:true,
                        value:'newWord'
                      }
                    });

但是做 aconsole.log(customEvent1)会产生一个Object.

对比一下:

var customEvent2 = new CustomEvent("newWord", { 
                     detail: {
                      word: "hola",
                      translation: "hi",
                     },
                     bubbles: true,
                     cancelable: true
                   });

您将看到运行console.log(customEvent2);将产生一个CustomEvent.

因此,当您尝试在上述对象上调用addEventListener()and时,它将失败,因为那是一个,而不是一个。您还需要执行一些步骤才能将其转换为完整的对象,这基本上是已经在做的事情。dispatchEvent()customEvent1ObjectEventcustomEvent1Eventnew CustomEvent()

小提琴在这里可用。

于 2014-11-18T18:20:02.587 回答
0

我认为它应该是这样的:

obj.addEventListener("newWord", function(e) {alert(e.detail);});

var wordCreated = Object.create(CustomEvent.prototype, {
  "newWord": 
    {
        detail: {
            word: "hola",
            translation: "hi",
        },
        bubbles: true,
        cancelable: true
    }
});
于 2014-11-18T17:58:30.517 回答