javascript - 使用原型(prototype)继承在 Javascript 中进行事件处理

标签 javascript events event-handling dom-events

我正在尝试在 JavaScript 中启用事件处理。这是我到目前为止所拥有的:

function Field(args) {
    this.id = args.id;

    this.name = args.name ? args.name : null;
    this.reqType = args.reqType ? args.reqType : null;
    this.reqUrl = args.reqUrl ? args.reqUrl : null;
    this.required = args.required ? true : false;
    this.error = args.error ? args.error : null;

    this.elem = document.getElementById(this.id);
    this.value = this.elem.value;

    this.elem.addEventListener('onblur', this, false);
    this.elem.addEventListener('click', this, false);
    this.elem.addEventListener('change', this, false);
    console.log(JSON.stringify(this.elem.value));

}

function FormTitle(args) {
    Field.call(this, args);
}

Field.prototype.getValue = function() { return Helpers.trim( this.value ) };

Field.prototype.sendRequest = function () {

};

Field.prototype.click = function (value) {
    alert("click");  
};

Field.prototype.onblur = function (value) {
    alert("onblur");  
};

Field.prototype.change = function (value) {
    alert("change");  
};

Field.prototype.dblclick = function (value) {
    alert("dblclick");  
};

Field.prototype.handleEvent = function(event) {
    switch (event.type) {
    case "click": this.click(this.value);
    case "onblur": this.onblur(this.value);
    case "change": this.change(this.value);
    case "dblclick": this.dblclick(this.value);
    }
};

// inheritProtootype uses parasitic inheritance to inherit from the Field's prototype
// and then assign the results to FormTitle's prototype.
inheritPrototype(FormTitle, Field);

var title = new FormTitle({name: "sa", id: "title"});

但是由于某种原因,所有事件都会同时触发。例如,当我单击表单中的“标题”字段时,不是仅触发 Click 事件,而是触发所有四个事件。

我做错了什么?

最佳答案

简单。在每个 case block 的末尾,使用 break; 语句将其与每个后续 block 分开。

关于javascript - 使用原型(prototype)继承在 Javascript 中进行事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610574/

相关文章:

javascript - 如何通过javascript捕获浏览器的事件

javascript - onsubmit 处理程序无法捕获使用链接中的 submit() 提交的表单

javascript - 用 Javascript 制作我自己的事件抛出器

javascript - 在页面加载时调用上面定义的 Javascript 方法

c# - 在 C# 中从 DLL 生成自定义事件

javascript - Native-React + Expo : Unable to resolve "@expo/vector-icons/fonts/Ionicons.ttf" from "src/boot/setup.js"

jquery - 事件发生后输入框的 keypress、keydown、keyup 值

c# - 事件处理程序递增循环问题

javascript - Google 脚本不会返回 Google 电子表格中的超链接

javascript - 在 node.js 应用程序中读取文件时出现奇怪的 unicode 字符