Recursive template with knockout js

后端 未结 4 509
逝去的感伤
逝去的感伤 2020-12-09 02:03

Is it possible to create a recursive template only with knockout js?

I have a knockout object:

function FormElementNode(children, text, value) {
   v         


        
4条回答
  •  鱼传尺愫
    2020-12-09 02:28

    Recursive Custom Binding

    Another solution, after reading that templates were slower I'm looking at going with recursive binding.

      ko.bindingHandlers.nestMe = {
          init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
      
          },
          update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
              var observable = valueAccessor() || { };
              var unwrapped = ko.unwrap(observable);
      
              ko.utils.setHtml(element, '
    • '+unwrapped+'
    • '); } }; var rootModel = function(name, children) { this.name = ko.observable(name); this.children = ko.observableArray(children); }; var basemodel = new rootModel('test'); basemodel.children.push(new rootModel('aaa',[new rootModel('111'),new rootModel('222')])); basemodel.children.push(new rootModel('bbb')); basemodel.children.push(new rootModel('ccc',[new rootModel('333'),new rootModel('444')])); ko.applyBindings(basemodel);

      Having the opportunity to play with data before the recursion should come in handy.

      JSFiddle

    提交回复
    热议问题