Kendo UI: 如何用 Remove/Add 交换 DOM 个元素

Kendo UI: How to swap DOM elements by Remove/Add

https://jsbin.com/jigefipiye/edit?html,console,output

我有 2 个模板,一个使用可见和不可见绑定,一个使用 #if () #

 <div>Template 1</div>
  <div id="to-bind1" data-bind="source: Data" data-template="template1"></div>

  <div>Template 2</div>
  <div id="to-bind2" data-bind="source: Data" data-template="template2"></div>

  <script id="template1" type="x"> 
    <li>
      # if (Readonly) { #
          <span data-bind="text: Val"></span>
      # } else { #
          <input data-bind="value: Val" />
      # } #
    </li>
  </script>


  <script id="template2" type="x"> 
    <li>
      <span data-bind="visible: Readonly, text: Val"></span>
      <input data-bind="invisible: Readonly, value: Val" />
    </li>
  </script>


  <script>
    var toBind1 = $("#to-bind1");
    var toBind2 = $("#to-bind2");

    var vm = kendo.observable({
      Data: [{
        Readonly: true,
        Val: "Woot!"  
      }],
    });

    kendo.bind(toBind1, vm);
    kendo.bind(toBind2, vm);

    setTimeout(function() {
      console.log('dfs')
      vm.get('Data')[0].set('Readonly', false);
    }, 5000)
  </script>

5 秒后,模板 2 切换为输入框,模板 1 保持不变

问题是在 template2 中隐藏了输入 我想要实现的是将输入与 span 交换,反之亦然,而不是隐藏它

类似于 knockoutJS 中的 if 绑定 https://knockoutjs.com/documentation/if-binding.html

if (and ifnot) play a similar role to the visible (and hidden) bindings. The difference is that, with visible, the contained markup always remains in the DOM and always has its data-bind attributes applied—the visible binding just uses CSS to toggle the container element’s visiblity. The if binding, however, physically adds or removes the contained markup in your DOM, and only applies bindings to descendants if the expression is true.

https://jsbin.com/lavunidapo/edit?html,console,output

这表明你想要什么我认为你想要实现(也许)。它从初始状态更改为 Readonly 并重新呈现两个项目模板。但要做到这一点,我们必须将对象从数组中取出并将其重新推入数组,以便项目模板再次重新呈现。然后它将 运行 看起来像这样的 JS 部分:

var $kendoOutput, 
    $kendoHtmlEncode = kendo.htmlEncode;
with(data) { 
    $kendoOutput=' \n <li>\n '; 
    if (Readonly) {
        ;$kendoOutput+='\n <span data-bind="text: Val"></span>\n '; 
    } else { 
        ;$kendoOutput+='\n <input data-bind="value: Val" />\n ';
    } ;
    $kendoOutput+='\n </li>\n ';
}
return $kendoOutput;

在使用上述代码呈现 LI 后,便会设置绑定。如果绑定到的字段发生变化,绑定将重新评估。但是改变的东西不会重新渲染模板(即它不会再次 运行 上面的 JS)你必须替换整个项目才能让上面的脚本重新 运行.