2017-05-03 8 views
-1

backbone.js 코드에 어떤 문제가 있습니까?
제품 페이지는 모델의 기본 값은 다음

내 모델입니다
콘솔에 내가 올바른 데이터를 볼 수 있지만 ... ... 표시됩니다로드 할 때 :모델보기는 기본값만 표시

var app = app || {}; 
app.Product = Backbone.Model.extend({ 
    defaults: { 
     coverImage: 'img/placeholder.png', 
     id: null, 
     name: 'Unknown', 
     price: '100' 
    } 
}); 

컬렉션 :

var app = app || {}; 
app.ProductList = Backbone.Collection.extend({ 
    model: app.Product, 
    url: 'php/listProducts.php' 
}); 

내보기 있습니다 :

var app = app || {}; 
app.ProductItemView = Backbone.View.extend({ 
    template: _.template($('#productPage').html()), 

    initialize: function(options) { 
     var id = options.id; 
     this.model = new app.Product(); 
     this.collection = new app.ProductList(); 
     this.collection.fetch({ 
      success: function(collection){ 
       console.log(collection.toJSON()); 
       console.log('Collection models: ', collection.models[id-1]); 
       this.model = collection.models[id-1]; 
       console.log('This model: ', this.model); 
      } 
     }); 

     this.render(); 
    }, 

    render: function() { 
     this.$el.html(this.template(this.model.attributes)); 
     return this; 
    } 


}); 

라우터 : 0

var app = app || {}; 
app.Router = Backbone.Router.extend({ 
    routes: { 
     "product/:id": "productPageShow" 
    }, 

    initialize: function() { 
     this.$content = $("#product-list"); 
    }, 

    productPageShow: function(id) { 
     app.prodItView = new app.ProductItemView({ id: id }); 
     this.$content.html(app.prodItView.el); 
    } 

}); 

$(function() { 
    new app.Router(); 
    Backbone.history.start(); 
}); 
내 템플릿 :

<div class="container">  
    <div id="product-list"></div> 
</div> 

<script id="productPage" type="text/template"> 
    <div> 
     <img src="<%= coverImage %>" class="img-responsive" style="width:100%" alt="<%= name %>"> 
    </div> 
    <div> 
     <h2><%= name %></h2> 
    </div> 
    <div> 
     <h3><%= price %></h3> 
    </div> 
</script> 

콘솔 이미지 :

console image

+0

[백본 : 서버에서 가져온 데이터를보기에 표시하지 않음] 가능한 복제본 (http://stackoverflow.com/questions/15330013/backbone-fetched-data-from-server-not- display-on-view) –

답변

1

이 '가져 오는 것은'때문에 render() 항상 success() 콜백 전에 호출됩니다 비동기 작업을하기 때문에 발생 전화 번호 : fetch()

일부 여분의 자원은 당신이 원하는 경우 :

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

http://backbonejs.org/#Model-fetch

initialize 방법에 코드를 시각적으로 실행 순서를 설명하기 위해 :

var app = app || {}; 
app.ProductItemView = Backbone.View.extend({ 
    template: _.template($('#productPage').html()), 

    initialize: function(options) { 
     // 1 
     var id = options.id; 
     // 2 
     this.model = new app.Product(); 
     // 3 
     this.collection = new app.ProductList(); 
     // 4 - fetch is only called and ajax request is sent to your backend. 
     //  success callback is still not called 
     this.collection.fetch({ 
      success: function(collection) { 
       // 6 - when you get the data from the server the callback is called 
       //  but the page is already rendered at this time 
       console.log(collection.toJSON()); 
       console.log('Collection models: ', collection.models[id-1]); 
       this.model = collection.models[id-1]; 
       console.log('This model: ', this.model); 
      } 
     }); 

     // 5 
     this.render(); 
    }, 

    render: function() { 
     this.$el.html(this.template(this.model.attributes)); 
     return this; 
    } 
}); 

수정해야 꽤 간단하다. 성공 콜백의 맨 아래에있는 render 메소드를 호출하면된다. 뷰의 올바른 컨텍스트 D 바인딩 :

또한
var app = app || {}; 
app.ProductItemView = Backbone.View.extend({ 
    template: _.template($('#productPage').html()), 

    initialize: function(options) { 
     var id = options.id; 
     this.model = new app.Product(); 
     this.collection = new app.ProductList(); 
     this.collection.fetch({ 
      success: _.bind(function(collection) { 
       console.log(collection.toJSON()); 
       console.log('Collection models: ', collection.models[id-1]); 
       this.model = collection.models[id-1]; 
       console.log('This model: ', this.model); 

       // Moved render call here 
       this.render(); 
      }, this) 
     }); 

    }, 

    render: function() { 
     this.$el.html(this.template(this.model.attributes)); 
     return this; 
    } 
}); 

, 일반적인 조언 .. 콜렉션으로 제공 get 방법을 사용 .. 직접 컬렉션 모델을 선택하지 않고 통과 결코 것처럼 모델 id 당신 필요 .. 사용 collection.get(mnodelId) 이상 collection.models[arrayIndexOfTheModel]

+0

마리오는 귀하의 답변과 조언을 많이 주셔서 감사합니다! 그것은 작동합니다! – Vovix

+1

'.fetch' 함수는'_.bind' 사용을 피하는'context' 옵션을 취할 수 있습니다. –

+0

@ EmileBergeron - 사실입니다. 백본에서 일하는 수년 동안 나는 그것을 눈치 채지 못했습니다. 문서에 없으므로 이제는 소스 코드에서만 확인했습니다. 'context'가 대개 마지막 매개 변수로 전달 되었기 때문에 이상합니다. 더 적은, 훌륭한 팁! 감사 :) – Mario