2013-03-21 1 views
3

내가javascript 생성자를 사용하여 html 요소를 만드는 방법은 무엇입니까?

function Person(name){ 
    this.name = name 
} 

Person.prototype.sayhi = function(){ 
    return this.name+' says hi !!! ' 
} 
var bob = new Person('bob') 
bob.name // bob 
bob.sayhi // bob says hi !!! 

같은 자바 스크립트 생성자의 기본 개념을 이해하지만 난 실제 웹 애플리케이션에 앨범을 만들려면 말할 수, 서버는 각 배열을 JSON 데이터의 배열

like:[{'id':1,'album_name':'test','user':'user_id'}] 

을 보내 항목이 앨범이어야합니다. 이제이 앨범을 div 요소으로 만들고 싶습니다. 어떻게해야합니까?

내가이 원하는 이유는 내가 진짜 div 요소로 앨범을 구성 할 수 있다면, 내가이

Album.prototype.open = function(){ 
    //some action 
} 
album = new Album(jdata) 

album.click(function(){ 
    this.open() 
}) 

이 가능,이 생성자를 정의하는 방법, 내가이있을 수 있습니다 생각됩니다 할 수 있다는 것입니다 정말 나를 혼란시키는 생성자 반환 값과 관련이 있습니다 !!!

+0

() {}'가능한'Person.constructor = 함수가 실제로있다 :

작업을 예를 들어 당신은에서 볼 수 있습니다. –

+1

@JaredFarrish 생성자의 생성자에 액세스하거나 변경하는 것은 특히 유용하지 않습니다. –

+0

당신은 어떤 생성자의 생성자를 참조하고 있습니까? –

답변

-2

나는 당신의 접근 방식이 잘못되었다고 생각합니다. 클라이언트 측 템플릿 엔진 (예 : Handlebars.JS)을 사용하여 응답 JSON 객체를 렌더링해야한다. 이 작업이 완료되면

는 그럼 빨리을 당신을 추천합니다 당신이 앨범 클래스가 준비 &이

var container=document.getElementById('myalbum001'), 
    album=new album(container); 

container.on('click',function(e){ 
    album.render(jdata); //You can get jdata by making AJAX call before this line 
    album.open() 
} 

처럼 사용할 수 있습니다 가지고

function album(container){ 
    this.container=container 
} 

album.prototype.open=function() { 
    container.show(); 
} 

album.prototype.renderHTML=function(jdata) { 
//This is handlebar.js code 

template=$('#albumTemplate').text(); 
compiledTemplate=Handlebars.compile(template); 
renderedTemplate=compiledTemplate(jdata); 
container.html(renderedTemplate); 
} 

처럼 생성자에게 & 프로토 타입 방법을 정의 Handlebar.js에서 한눈에보기

0

개체 키와 일치하는 클래스로 일부 템플릿 파일을 만든 다음 키를 순환하고 템플릿 파일을 채 웁니다. 예를 들면 :

정말 모든 요구에 맞게하지 않습니다 불구하고 획일적 시도의
function Album (album) { 
    this.template = $('#template').clone().removeAttr('id'); 
    this.album = album; 
} 

Album.prototype.html = function() { 
    var i, val; 
    for (i in this.album) { 
     if (!this.album.hasOwnProperty(i)) { 
     continue; 
     } 
     val = this.album[i]; 
     this.template.find("." + i).html(val); 
    } 
    console.log(this.template); 
    return this.template; 
} 

var foo = new Album({ 
    title: 'Cheap Thrills', 
    artist: 'Frank Zappa', 
    genre: 'Rock and Roll' 
}); 

$('#main').html(foo.html()); 

. 이 솔루션이 사용자의 필요에 맞지 않는 경우 조건 또는 조건을 설정할 수 있습니다. 예를 들어 데이터가 이미지 URL 인 경우 innerHTML을 설정하는 것이 그리 유용하지 않으므로 대신 'src'속성을 설정하거나 SRC 속성이있는 img 태그를 만듭니다.

템플릿 파일은 다음과 같습니다

<div class="album"> 
    <div class="user"></div> 
    <span class="foo"></span> 
    <textarea class="bar"></textarea> 
</div> 

여기에 빠른 바이올린 : 당신이 클래스를 사용하는 아이디어를 좋아하지 않는 경우에, 대신 data-attributes을 시도 http://jsfiddle.net/bxw7Z/

.

+0

이것은 whai 의미가 아니에요, 내가 원하는 건 진짜 div elememt를 반환하는 자바 스크립트 생성자입니다. 모든 프로토 타입 메소드를 자동으로 갖습니다. – paynestrike

+0

정확히, 템플릿을 반환하면됩니다. 편집 해 보겠습니다. –

1

다음을 수행 할 수 있습니다.

var i, data, Albom, albom; 

Albom = function Albom(data) { 
    var i, 
     div = document.createElement('div'); 

    for(i in data) { 
    div.setAttribute('data-'+i, data[i]); 
    } 

    div.innerHTML = data.album_name; 

    for(i in this) { 
    if(typeof this[i] === 'function') { 
     div[i] = this[i].bind(div); 
    } else { 
     div[i] = this[i]; 
    } 
    } 

    return div; 
}; 

Albom.prototype.open = function open() { 
    alert(this.getAttribute('data-id')); 
}; 

data = [ 
    {'id':1,'album_name':'test1','user':'user_id1'}, 
    {'id':2,'album_name':'test2','user':'user_id2'} 
]; 

for(i in data) { 
    albom = new Albom(data[i]); 
    document.body.appendChild(albom); 
} 

이제 new Albom(data) 제공 data 객체의 속성을 가지고 있으며,이 DOM 요소의 범위에서 실행됩니다 생성 요소 내부의 모든 프로토 타입의 속성과 기능을 가지고있는 새로운 DOM 요소를 생성합니다은 (그래서 당신은 그 안에 this를 참조 할 수 있습니다 행동 양식).

예를 들어 albom.open()으로 전화를 걸고 2이라는 경고가 팝업으로 표시됩니다. http://jsbin.com/isepay/10/edit

+0

이것은 내가 염두에두고있는 것인데, albom.hhh() (또 다른 프로토 타입 메소드)라고 부를 수는 없다. http://jsbin.com/isepay/6/edit; 그것은 반환 값 때문입니까? – paynestrike

+0

@chenliang 필요한 기능을 지원하도록 코드를 수정했습니다. 이제는 프로토 타입에서 모든 메서드를 호출 할 수 있습니다. – Vadim

+0

검색기가 반환 값에 대해 약간의 검색을 한 후에 작동한다고 생각하지 않습니다. 자바 스크립트 생성자에서 개체를 반환하면 "this"키워드가 손실 될 것입니다. 앨범 = 새 앨범 (jdata); 앨범 instanceof 앨범; false.but 어쨌든 고맙습니다 !!! – paynestrike

관련 문제