4

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?

4

1 回答 1

3

KO 在您调用 ko.applyBindings 时应用绑定。因此,如果您在调用 applyBindings 之后修改 dom。KO 不会知道新的 dom 元素。

您可以这样使用模板:

<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>

毛里齐奥编辑。使用此小提琴,因为其他链接似乎已损坏: 请参阅小提琴

于 2013-07-08T09:24:17.750 回答