0

I am trying to enable Event Handling in JavaScript. This is what I have so far:

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"});

For some reason however, all events are triggered at the same time. For example, when I click on the Title field in the Form, instead of only Click event triggering, all four events are triggered.

What am I doing wrong?

4

3 回答 3

3

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

于 2013-05-17T13:49:07.293 回答
2

您的switch语句遗漏了一些break语句,因此以防click所有四种方法都被执行。

但是,有一个比switch-statement 更好的选择:

Field.prototype.handleEvent = function(event) {
    var prop = event.type;
    if (prop in this) // && typeof this[prop] == "function"
        this[prop](this.value);
};

这将适用于所有事件而无需明确提及它们。

于 2013-05-17T13:53:38.470 回答
1

在你的 switch 语句中,你需要break在每个 case 之后都有一个。

switch (event.type) {
  case "click": this.click(this.value); break;
  case "onblur": this.onblur(this.value); break;
  case "change": this.change(this.value); break;
  case "dblclick": this.dblclick(this.value); break;
}

最后一个中断不是必需的,但最好包含它,因为您可能会添加其他案例。

于 2013-05-17T13:50:19.857 回答