Knockout components (not) binding on new content

后端 未结 1 1573
逝去的感伤
逝去的感伤 2021-02-05 11:48

Redacted question and example

I\'m trying to get Knockout components to bind after the initial ko.applyBindings(); so I can add custom elements dynamicall

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 12:03

    The component binding doesn't happen magically: it happens when you call ko.applyBindings();. At this moment, the bound HTML is searched for components, and they are bound.

    Later on, when you dynamically add a new component to the page, it's not bound, unless you explicitly bind it. So, in your code, the component is fully ignored.

    As stated, what you need to do is to explicitly bind it. But you must take into account that you cannot bind nodes that have already been bound. However it's extremely easy to create a node with jquery, append it to the DOM, and bind it. There is a syntax to specify the viewmodel and the node to which you want to bind it: ko.applyBindings(viewModel, node);

    Here you have a full working sample in jsfiddle. This is the code in that fiddle:

    HTML:

    Here's a widget, declared inline:

      
      

    Widgets will be appended here

    JavaScript:

    ko.components.register('like-widget', {
        template: '
    This is the widget
    ' }); ko.applyBindings() $('#btnAdd').on('click', function() { // Create your widget node var $newWidget = $(''); // Append it to your "append area" $('#addZone').append($newWidget); // Apply bindings to the newly added node ko.applyBindings({}, $newWidget[0]); });

    NOTE: when calling apply bindings I pass an empty objet: don't pass a null, or you'll get an error. If your template includes a viewmodel, it will be used independently of the passed view model.

    NOTE: $newWidget is a jquery object. $newWidget[0] is the first (and only, in this case) DOM element of the jQuery object, as required by applyBindings

    0 讨论(0)
提交回复
热议问题