2016-01-28 36 views
1

我創建了一個自定義敲除綁定,將給定div包裝在擴展器中。我的自定義綁定將給定的內容div移動到擴展器的contant-container div。移動內容後,內容子節點的挖空綁定將不再起作用(例如,點擊內容div中的按鈕的綁定)。因此我必須重新應用淘汰賽的綁定。如何部分(重新)綁定到後代敲除?

這在大多數情況下適用。但是,如果content div包含例如淘汰賽的foreach綁定,則重新應用綁定意味着某些內容被複制。膨脹機的

用法示例綁定:

<div  
    data-bind="expander: { title: 'dataCollectionForms'}"> 
<div> 
    <div class="expander-content"> 
    <button  
     data-bind="click: $root.addAction, text: 'Hinzufügen'"></button> 
    <div 
     data-bind="foreach: listOfButtons"> 
     <button  
     data-bind="click: $root.buttonClickAction"> 
     </button> 
    </div> 
    </div> 
</div> 
</div> 

我的用於移動內容的div代碼:

function moveExpanderContentToContentContainer($contentContainer, expanderContent) { 
    try { 

    //Move the expander content to the content container 
    //The content will not be cloned but moved. For more info see: 
    //https://api.jquery.com/append/ 
    var $expanderContent = $(expanderContent); 
    $contentContainer.append($expanderContent); 
    $contentContainer.addClass('expander-content-container panel-body'); 
    $expanderContent.addClass('expander-content'); 

    ko.applyBindingsToDescendants(bindingContext, expanderContent); 

    } catch (appendException) { 
    var errorMessage = 'Could not append expander-content to expander-content-container.'; 
    logger.logError(errorMessage, appendException, self, true); 
    } 

}

  • 如果刪除了線

ko.applyBindingsToDescendants(bindingContext,expanderContent);

我的三個按鈕的點擊動作不工作了: enter image description here

  • 如果我繼續行,點擊操作運作,但按鈕複製: enter image description here

=>如何以修復 點擊綁定的方式更新移動內容的綁定,並且不會重複我的按鈕?

=>如果這個移動的工作流程根本不起作用,那麼創建一個自定義挖空綁定的更好方法是將可摺疊擴展器中的給定內容封裝起來?

我能找到一些相關的文章,但沒有解決我的具體問題:

+0

我認爲這將有助於您嘗試對問題進行最小程度的重現。我沒有看到任何理由,只是移動一個div會使綁定無效,除非您希望移動來更改綁定的上下文。您可能想使用模板來代替。 –

回答

1

我通過不移動內容div來解決問題,只是在其周圍構建擴展器。

我原來的策略是有一個可重用的擴展視圖+視圖模型,並將內容div從原始位置移動到新組成的擴展視圖。我想,移動已經綁定的內容不是好主意。

新戰略適應已經存在的div並僅構成擴展器的頭部。

不過謝謝你的想法。

0

我用下面的代碼用於重建所傳遞的DOM元素(具有視圖模型+模板選擇器)的內容:

function renderIntoElement(element, viewModel, templateSelector) { 
    templateSelector = templateName || "#myTemplateId"; 
    var $element = $(element); 
    var templateHtml = $(templateSelector).text(), 

    $element.children().remove(); 
    $element = $element.append(templateHtml), 

    ko.applyBindings(viewModel, $element.children()[0]); 
} 

希望這有助於。