Html knockout with another binding inside

I use knockout to dynamically load content onto parts of a page using HTML binding.

the problem is that the html I want to link has to execute the onclick function call and I need information about the target and data that is easy to send by knockout.

something like that:

myFunction($parent, $data) 

HTML:

 <table> <tbody data-bind="foreach: rows" > <tr> <td data-bind="html: rowValue">this will be a link</td> </tr> </tbody> </table> 

Later, I set the value as a link with a knockout link inside:

 rowValue("<a href='#' data-bind=click:alert('hello')" + result.Data + "</a>"); 

Please check the fiddle here to see the full working code.

You can see the difference between the two lines that I wrote, if I do javascript onclick, this works, but obviously ko lacks late binding.

I have seen many questions about this, but cannot find it with the final answer.

I want to do this with KO, how can this be done? with patterns maybe?

+4
source share
1 answer

KO applies bindings when calling ko.applyBindings. Therefore, if you change dom after applicationBindings has been called. KO will not know about the new dom element.

You can use the template this way:

 <table> <tbody data-bind="foreach: sitesTable.rows" > <tr data-bind="foreach: row"> <td data-bind="template: 'myTemplate' "></td> </tr> </tbody> </table> <br/> <a href="#" onclick="getNewData()"> click here </a> <script id="myTemplate" type="text/html"> <a href='#' data-bind="html: cellValue, click: openAlert"> click </a> </script> 

Edit Maurizio. Use this script as other links will be broken: See the fiddle

+3
source

Source: https://habr.com/ru/post/1490235/


All Articles