2017-07-27 35 views
0

我正在使用DurandalJS與Knockout來加載頁面的數據。數據用ajax調用加載,所以數據在執行回調之前不可用。DurandalJS構圖調用敲擊兩次

發生什麼事情是,當數據最終加載,我打電話ko.applyBindings(model),它已經試圖綁定數據一次,它會引發錯誤,指出數據不能綁定兩次。我想阻止Durandal這樣做,並允許我手動應用綁定。

代碼:

define(['plugins/router', 'durandal/app', 'gcharts', 'jquery'], function (router, app, gcharts, $) { 

    var projectStatsModel = function (data) { 

     this.projectId = data.projectId; 
     this.projectName = data.projectName; 
     this.projectDescription = data.projectDescription; 
     this.projectPlatform = data.projectPlatform; 

     this.projectPointsLabel = "Total Points: " + data.projectNumPoints; 
     this.projectStoriesLabel = "Total Stories: " + data.projectNumStories; 
     this.projectCreatedDateLabel = "Created " + data.projectCreationDate; 
     this.projectUpdateDateLabel = "Last Updated " + data.projectModifyDate; 

     this.projectEpics = data.projectEpics; 
     this.projectStories = data.projectStories; 

     return this; 
    } 

    var ctor = function() { 

     function drawPage(data) { 
      var model = projectStatsModel(data); 
      ko.applyBindings(model); 
     } 

     function loadData() { 

      var projectId = router.activeInstruction().params[0]; 

      $.ajax({ 
       url: '/ClubhouseData/GetProjectDetails', 
       data: { 
        'projectId': projectId 
       }, 
       type: 'GET', 
       cache: 'false', 
       success: function (result) { 
        console.log(result); 
        drawPage(result); 
       } 
      }); 
     } 

     ctor.prototype.activate = function() { 
      loadData(); 
     } 
    }; 


    return ctor; 
}); 

回答

0

作爲安全預防措施之前,我申請綁定,我總是檢查元素是否已經在我的應用程序的約束。

if (isBound("container")) 
    ko.cleanNode(document.getElementById('container')); 
// Bind 
ko.applyBindings(viewModel, document.getElementById("container")); 

我一個isBound方法:

var isBound = function (id) { 
    if (document.getElementById(id) != null) 
     return !!ko.dataFor(document.getElementById(id)); 
    else 
     return false; 
}; 

這將防止您的錯誤,從發生的歷史,因爲它會運用它,如果已經綁定之前取消綁定。