javascripthtmlknockout.jsknockout-2.0

knockout html binding with another binding inside


I'm using knockout to dynamically loading content into parts of the page, using the HTML binding.

the problem is that the html I want to bind has to do call a function onclick and I need the information about the target and the data that knockout easily send.

something like this:

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 to be a link with a knockout binding 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 2 lines I wrote, if I do a javascript onclick it works, but obviously ko is missing a late binding.

I've seen many questions about this but can't find one with a definitive answer.

I want to do this with KO, how can this be accomplished? with templates maybe?


Solution

  • KO applies bindings when you call ko.applyBindings. So if you modify the dom after applyBindings has been called. KO won't be aware of the new dom element.

    You can use 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 by Maurizio. Use this fiddle as the other linkseems to be broken: See fiddle