2017-05-24 44 views
0

採用淘汰賽,這是很簡單的填充循環與一些JSON data.Here在視圖中的循環:如何刪除我的綁定?

<div class="row" data-bind="foreach: VacationRequestNotes"> 
    <div class="col-lg-2"> 
     <span class="input-sm" style="white-space:nowrap;" data-bind="text: EmployeeName"></span> 
    </div> 
    <div class="col-lg-10"> 
     <span class="input-sm" data-bind="text: NoteText"></span> 
    </div> 
</div> 

然後腳本:

function ViewNotes(vactionRequestId) { 
    $.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) { 
     if (data != "error") { 
      ko.applyBindings({ 
       VacationRequestNotes: data 
      }); 
     } 
    }); 
} 

這個偉大的工程!至少,第一次。第二次,我得到

Uncaught Error: You cannot apply bindings multiple times to the same element.

我見過這裏的其他線程說我需要刪除綁定,但我在應用這些例子我在做什麼辛苦。

function ViewNotes(vactionRequestId) { 
    $.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) { 
     if (data != "error") { 
      ko.applyBindings({ 
       VacationRequestNotes: data 
      }); 
      ko.cleanNode(??? WHAT DO I PUT HERE ???); 
     } 
    }); 
} 
+0

你有沒有嘗試從另一端接近它,而不是從一個重複的代碼塊中應用你的綁定?您可以在準備好文檔時將它們應用一次,並更新ajax回調中的現有觀察值。 –

+0

嘗試做到這一點'ko.cleanNode(document.getElementsByTagName(「body」));' – muhihsan

+0

@Jason Solake:好的 - 是的,我在想同樣的觀點。新淘汰賽。試圖找出如何做到這一點。第一次加載頁面時,VacationRequestNotes將爲空。直到用戶點擊「查看備註」按鈕,它纔會包含任何內容。那麼在文檔準備好時我該如何綁定它? –

回答

0

終於得到它的工作:

$(document).on('ready', 
     function() { 
      masterVM = new VacationRequestsViewModel(); 
      ko.applyBindings(masterVM); 
     }); 

    function VacationRequestsViewModel() { 
     var self = this; 
     self.VacationRequestNotes = ko.observableArray(); 

     self.ViewNotes = function (vactionRequestId) { 
      $.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) { 
       if (data != "error") { 
        self.VacationRequestNotes(data) 
        $("#modalNotes").modal('show'); 
       } 
      }); 
     } 
    } 

然後,在HTML,而不是此鏈接:

<a href="" onclick="ViewNotes(3)">View Notes</a> 

它只是更改爲:

<a href="" onclick="masterVM.ViewNotes(3)">View Notes</a> 
0
function ViewNotes() { 
     var self = this;  
     self.VacationRequestNotes = ko.observable(); 
     self.GetNotes = function(vactionRequestId) {   
     $.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) { 
      if (data != "error") { 
       self.VacationRequestNotes(ko.mapping.fromJS(data)); //requires the ko mapping.   
       //In vanilla JS you can use the map function. 
      } 
     });  
    }  
} 

$(function() { 
    var vm = new ViewNotes(); 
    ko.applyBindings(vm); 
}); 
+0

好的,非常感謝!一個問題:GetNotes如何執行? –

+0

vm.GetNotes(someParameter)。或者你可以將它綁定到按鈕或鏈接。我可以幫你做到這一點。 – Bruno

+0

後ko.applyBindings(vm) – Bruno