2013-07-06 32 views
0

我對Knockout相當陌生,我試圖使用jquery插件,它將自定義樣式應用於某些元素。但是因爲我有一個從ajax調用中獲取內容的頁面,並且所有元素都是通過敲除動態構建的,所以最初的jquery函數調用不知道頁面上有任何元素,因此沒有樣式應用於這些元素。敲除dom操作後回調jquery函數

所以我問的是如何在敲除完成操縱元素(DOM)後回調jquery函數?

現在我打電話jQuery的功能如下: -

$(document).on("load",function(){ 
    $(".element").callPlugin("add-style"); 
}); 

回答

6

applyBindings是同步的,所以你可以ko.applyBindings(VM)後調用callPlugin(下一行)。

ko.applyBindings(VM); 
$(".element").callPlugin("add-style"); 

或者,如果您多次更新UI,則可以使用custom bindings。假設.element<div>(也有可能是別的),你的標籤應該是這樣的:

<div class="element" data-bind="text: 'This is just some text which KO will bind', 
           updateUI: true"> 
This text will change. Wait for it.. 
</div> 

注意在data-bindupdateUI。這是對應的JS代碼吧:

ko.bindingHandlers.updateUI = { 
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){   
     // This will be called when the binding is first applied to an element 
     // Set up any initial state, event handlers, etc. here 
     $(".element").callPlugin("add-style"); 
    }, 
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     // This will be called once when the binding is first applied to an element, 
     // and again whenever the associated observable changes value. 
     // Update the DOM element based on the supplied values here. 
     $(".element").callPlugin("update-style"); // just saying 
    } 
}; 

這會讓你的插件初始化,並在任何更改完成到DOM自動更新。

希望這有助於!

+0

將此標記爲正確的,因爲這是用很好的示例解釋的。我沒有使用自定義綁定,它的工作。謝謝。自兩天以來我一直在努力尋找解決方案。我很喜歡Knockout。 – shriek

+1

值得一提的是,當您使用'ko.options.deferUpdates = true;'時,'ko.applyBindings()'的繪畫是不同步的。因此,例如,如果您嘗試直接獲取'svg.getCTM()',它將不會按照建議工作。 – kernel