user
user

Reputation: 99

Overriding parent prototype method for event handling

I am using the following code jsFiddle to work with form fields and events. I have previously asked two questions regarding this and they have helped me tremendously. Now I have a new problem/question.

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

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

Field.prototype.addEvent = function (type) {
    this.elem.addEventListener(type, this, false);
};

// FormTitle is the specific field like a text field. There could be many of them.
function FormTitle(args) {
    Field.call(this, args);
}

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

FormTitle.prototype.blur = function () {
    alert("FormTitle Blur");
};

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

inheritPrototype(FormTitle, Field);
var title = new FormTitle({name: "sa", id: "title"});
title.addEvent('blur');


function inheritPrototype(e, t) {
    var n = Object.create(t.prototype);
    n.constructor = e;
    e.prototype = n
}

if (!Object.create) {
    Object.create = function (e) {
        function t() {}
        if (arguments.length > 1) {
            throw new Error("Object.create implementation only accepts the first parameter.")
        }
        t.prototype = e;
        return new t
   }
}

The problem is that I want to override the parent method (Field.prototype.blur) and instead use FormTitle.prototype.blur method for the title object. But the object keeps referencing the parent method and the alert always shows 'Field blur' instead of 'FormTitle Blur'. How can I make this work?

Upvotes: 0

Views: 392

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

You are defining a method in the FormTitle prototype, then replacing the whole prototype with another object using inheritPrototype.

You have to swap the order. First you call this:

inheritPrototype(FormTitle, Field);

Then you set onblur on the prototype object you just created:

FormTitle.prototype.blur = function () {
    alert("FormTitle Blur");
};

http://jsfiddle.net/zMF5e/2/

Upvotes: 1

Related Questions