2013-07-23 1 views
1

에 추가 할 때 내가 모델백본 가져 오기 및 모델 컬렉션

Item = Backbone.Model.extend({....}) 
Apvdtl = Backbone.Model.extend() 

과 모음

Apvdtls = Backbone.Collection.extend({ 
    model: Apvdtl 
}) 

를 포함하고 Apvdtl 모델 으로 컬렉션을 채 웁니다 fiddle here

이 모델을 재설정 예

apvdtls.add([{ itemid: 'c4676cef679a11e28b7a3085a942bd8e', qty: 10 }, 
      { itemid: '1da17339690f11e285d63085a942bd8e', qty: 5 }]) 

이보기

grid1

하지만 메신저 일을하려고하는에이 ID로 항목을 가져 오는하여이

grid2

같은보기를 만들기 위해입니다 생성 이 주소에 JSON File

ApvdtlView = Backbone.View.extend({ 
    tagName: 'tr' 
    initialize: function(){ 
     this.model.on('change', this.render, this); 
     this.template = _.template('<td><%=itemid%></td><td><%=qty%></td>'); 
    }, 
    render: function(){ 

     item.set({'id': this.model.get('itemid')}); 
     // item = {id: 'c4676cef679a11e28b7a3085a942bd8e'} 

     item.fetch(); // but this doesnt get the data 
     // this should contain this data after i fetch 
     // item = {"id": "c4676cef679a11e28b7a3085a942bd8e", 
     //   "code": "prp125", "descriptor": "Paper", "price": "7.00"} 

     // build new data to render 
     var data = { 
      "itemid": item.get('descriptor'), 
      "qty": this.model.get('qty') 
     } 

     this.$el.html(this.template(data)); 
     //this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

답변

1

처음 아약스는 비동기입니다. 따라서 응답이 언제 다시 오는지 알 수 없으므로 이벤트에 첨부하는 것이 좋습니다.

ApvdtlView = Backbone.View.extend({ 
    tagName: 'tr', 
    initialize: function() { 

      // This listens to the sync and change event and renders the item 
     this.listenTo(this.model, 'change sync', this.render); 
     this.template = _.template('<td> <%=itemid%> </td>' + 
      '<td><%=qty%></td>'); 
     this.model.fetch(); 

    }, 
    render: function() { 

     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

url 다음 속성은 서버로부터 인출됨에 따라 모델 ApvdtlView에 설정되어야한다.

다음은 십자가 원본 정책을 위반하는대로 다른 도메인이기 때문에 도메인

urlRoot: 'https://raw.github.com/jrsalunga/prism2/master/www/api/item.json' 

에서이 URL을 칠 수 없다. 당신은 이제 네트워크 탭에서 가져온하지만 콜백 처리해야하기 때문에 오류가 발생합니다 데이터를 볼 수있는이

Check Fiddle

JSONP request Fiddle

를 얻을 수 jsonp를 사용할 필요가 서버 측

+0

답변 해 주셔서 감사합니다! =)하지만 내보기 ('ApvdtlView')는 URL이 필요 없다. 메신저가 단지 그것을 사용하여 콜렉션 ('Apvdtls')에서 "데이터"를 얻을 수 있기 때문이다. 'https : // raw.github.com/jrsalunga/prism2/master/www/api/item.json' URL에 관한 것입니다. 단지 "데이터를 가져오고"저장하려고하지 않았습니다. 뷰 ('ApvdtlView')에 대한 데이터는 모델 ('Item')과이 코드의'apvdtls.add ([{itemid : 'c4676cef679a11e28b7a3085a942bd8e', qty : 10}]) 모델에서 가져온 것입니다. 내 'ApvdtlView' 모델 ('Apvdtl')이 아닌 내보기 ('ApvdtlView')를위한 새로운 데이터 세트 – jrsalunga