2012-01-27 1 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. 

잘 작동합니다. 그러나 나는이에 도착하기에 충분한 추상적 내 코드에 노력하고있어에 appendChild가 foo를 호출 할 때 foo.input가 자동으로 반환됩니다

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

.

지금, 나는 내가 기능을 구성 년대에 입력 요소를 반환하는 내 래퍼 클래스를 수정할 수 있다는 걸,하지만 난 그렇게 할 때, 나는 수업 방법 중 하나를 호출 할 수있는 기능 상실 :

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

을 그래서 개체의 기본 동작을 재정의하고 .appendChild가 foo에서 호출 될 때 foo.input을 반환하는 방법이 있습니까? 당신이 당신의 객체의 메소드 append()을 만들 경우

답변

1

당신이 바이올린을 볼 추상적 인 더 이상이

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(); 

document.body.appendChild(foo);을 수행 할 수있을 것입니다 : http://jsfiddle.net/yJ44E/
참고 : 당신은 또한에 동의 그래서 append() 방법을 변경할 수 요소를 추가하려는 인수로 node.

+0

아! 좋은 생각이야!/* 이마 슬랩 */ 클래스에 appendTo (element) 메소드를 작성할 수 있습니다. 그것은 내가 원래 가지고 있던 것보다 훨씬 더 깨끗합니다. 감사!!! –

+0

예. 하나의 메소드 append()를 사용하고 메소드에 요소가 전달되지 않으면 document.body를 기본 노드로 사용할 수 있습니다 – fcalderan