Daniel Szabo
Daniel Szabo

Reputation: 7281

Create default behavior for when appendchild is called on an object

I'm working on creating wrapper classes for some HTML elements and I'd like to know if there is a way to specify default behavior for my class when .appendChild is called on it.

// Very simple textbox wrapper class
function MyWrapperClass(){
    this.input = document.createElement('input'); // textbox
}
MyWrapperClass.prototype.setValue = function(v){
    this.input.value = v;
}

// Add instance of my wrapper class to DOM
var foo = new MyWrapperClass();
document.body.appendChild( foo.input ); // Works fine.

That works well enough. But I'm trying to abstract my code enough to get to this:

// Add instance of my wrapper class to DOM
var foo = new MyWrapperClass();
document.body.appendChild( foo );

where foo.input is automatically returned when appendChild is called on foo.

Now, I realize that I can modify my wrapper class to return the input element in it's constructing function, but when I do that, I lose the ability to call any of the class methods:

// Modified wrapper, returns input on instancing
function MyWrapperClass(){
   this.input = document.createElement('input'); // textbox
   return this.input
}

var foo = new MyWrapperClass();
foo.setValue('Hello'); // ERROR: html input element has no setValue method

So is there any way to override the default behavior of the object and return foo.input when .appendChild is called on foo?

Upvotes: 1

Views: 328

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123407

if you create a method append() of your object you would be able to abstract more than doing document.body.appendChild( foo );

function MyWrapperClass(){
   this.input = document.createElement('input'); // textbox
   return this;
}
MyWrapperClass.prototype.setValue = function(v){
    this.input.value = v;
}
MyWrapperClass.prototype.append = function(){
    document.body.appendChild(this.input)
}


var foo = new MyWrapperClass();
foo.setValue('test');
foo.append();

see this fiddle: http://jsfiddle.net/yJ44E/
Note: you could also change the append() method so to accept the node as an argument in which you want to append the element.

Upvotes: 1

Related Questions