2012-01-27 15 views
1

我正在爲某些HTML元素創建包裝類,我想知道是否有方法在調用.appendChild時爲我的類指定默認行爲在上面。在對象上調用appendchild時創建默認行爲

// 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. 

這很好。但我試圖抽象我的代碼足以達到這個:

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

其中foo.input自動返回時,當在foo上調用appendChild。現在

,我意識到,我可以修改我的包裝類返回輸入元素在它的構造函數,但是當我這樣做,我失去調用任何類方法的能力:

// 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 

那麼在foo上調用.appendChild時,有什麼方法可以覆蓋對象的默認行爲並返回foo.input?

回答

1

如果您創建對象的方法append()你將能夠抽象超過做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(); 

看到這個小提琴:http://jsfiddle.net/yJ44E/
注意:您也可以改變append()方法,以便接受節點作爲你想追加元素的參數。

+0

啊!好想法!/*前額巴掌*/ 我可以爲該類編寫appendTo(element)方法。這比我原來的要乾淨得多。謝謝!!! – 2012-01-27 20:08:59

+0

是的。如果沒有元素傳遞給方法,可以使用單個方法append()並將document.body用作默認節點 – fcalderan 2012-01-27 20:12:16

相關問題