Dynamically add data-bindings to elements pn page load ?

54 views
Skip to first unread message

Shawn

unread,
Jul 3, 2022, 9:12:18 AM7/3/22
to KnockoutJS
On a site i have some pages are dynamically generated with content from several sources.
Is it possible to dynamically add the "data-bind" attributes to specific elements on page load with knockout.js?


Julio Di Egidio

unread,
Jul 6, 2022, 2:49:32 PM7/6/22
to KnockoutJS
Yes, you can add elements to the page with all the needed data-bind attributes set, then you can do the view binding and it should just work.

It can get more complicated if you manipulate the DOM after the initial view binding...

HTH,

Julio

LG Song

unread,
Jul 6, 2022, 5:52:24 PM7/6/22
to KnockoutJS
Yes, you can do that by call the applybindings to the newly added elements

something like 

var detail = $('<div class="modal fade"  tabindex="-1" role="dialog" aria-labelledby="alertModal" aria-hidden="true" data-backdrop="static" id="modal">' +
  '<div class="modal-dialog modal-dialog-centered modal-xl" role="document">'+
     '<div class="modal-content">' +
      '<div class="modal-header">' +
                '<h5 class="modal-title">' + title + '</h5>' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
                '</button>'+
      '</div>' +
      '<div class="modal-body">' +
        '<div class="compNode"></div>' +
      '</div>' +
      '<div class="modal-footer">  <button type="button" class="btn btn-primary btnOk">Ok</button>'+
        '</div></div></div></div>');
 detail.append();

 ko.applyBindingsToNode($('div.compNode', detail)[0], { component: { 'name': msg, 'params': vm } }, vm);
Reply all
Reply to author
Forward
0 new messages