2017-12-24 31 views
0

HTML :방지 HTML 로딩 녹아웃 매핑 데이터 로딩 전에

<div id="knockoutBinding"> 
    <div class="toolbar" data-bind="template: 'user-portfolio-entry' "></div> 
</div> 

<script id="user-portfolio-entry" type="text/html"> 
<!-- ko if: vm.currentPortfolioEntry().hasOwnProperty('Step') --> 
//other stuff 
<!-- /ko --> 
</script> 

자바 스크립트 :

var UserPortfolioViewModel = function() { 
     var self = this; 

     self.currentPortfolioEntry = ko.observable(null); 
     $.ajax({ 
      type: "POST", 
      url: getPortfolioEntryUrl, 
      data: JSON.stringify(data1), 
      dataType: "json", 
      contentType: "application/json", 
      success: function (response) { 
       self.currentPortfolioEntry(ko.mapping.fromJS(response)); 
      }, 
      error: function (data) { 
       alert("fail"); 
      } 
     }); 
} 
var vm; 
    $(function() { 
     vm = new UserPortfolioViewModel(); 
     ko.applyBindings(vm, $("#knockoutBinding")[0]); 
    }); 

내가 얻을 오류 :

Uncaught TypeError: Unable to process binding "template: function (){return 'user-portfolio-entry' }" Message: Unable to process binding "if: function(){return vm.currentPortfolioEntry().hasOwnProperty('Step') }" Message: Cannot read property 'hasOwnProperty' of null

때 라인에 아약스 성공 성공 self.currentPortfolioEntry(ko.mapping.fromJS(response)); 그때 콘솔에서 vm.currentPortfolioEntry().hasOwnProperty('Step')의 값을 볼 수 있지만 그 당시 html은로드가 끝났으며 html로 데이터를 가져올 수 없습니다.

아약스 성공 후 html을로드하여 속성을 매핑 할 수있는 방법. 아니면 다른 방법으로이 오류를 해결할 수 있습니까?

답변

2

당신은 다음과 같은 변수가 종료하는지 테스트하기 위해 if를 리팩토링 수 :

<!-- ko if: vm.currentPortfolioEntry() && vm.currentPortfolioEntry().hasOwnProperty('Step') --> 
+0

확인,이 변수가 존재하지만 재산'step'이 HTML 내부의 데이터가없는 말할 것이다하지 않을 것이다 로드 될 수 있지만 실제로 아약스 호출에서 올 것입니다 때문에 데이터를로드해야합니다. –

+0

@IrfanYusanif 나는 내가 이해하고 있는지 잘 모르겠다. ajax 호출 전에 'currentPortfolioEntry'는 null이 될 것이므로'if' 콘텐츠는 DOM에 추가되지 않습니다. 이 호출 후에'currentPortfolioEntry'가'Step'을 포함하면 내용이 표시됩니다. 너는 무엇을 더 원하니? –