Context of this when triggering method on root fro

2019-05-10 04:53发布

I have this very simple test view

<button data-bind="click: add">Add</button>
<table data-bind="foreach: items">
    <tr>
        <td data-bind="text: name"></td>
        <td><button data-bind="click: $root.remove">Remove</button></td>
    <tr>
</table>

Fiddle: http://jsfiddle.net/6PP5m/

The problem is that the context of this in the remove method is the child view model that fired the click event

I havent found a solution that I like, you can add a self variable in the contructor and use that instead of "this", but its more clean code and OO to use the "this" keyword

Fiddle: http://jsfiddle.net/Qn2CM/

You can also create a proxy function delegate but its still not very clean code

Fiddle: http://jsfiddle.net/gYhMr/

What I would like is to tell ko somehow to set the context of this to the correct correct scope ($root in this case) is it possible?

标签: knockout.js
1条回答
一纸荒年 Trace。
2楼-- · 2019-05-10 05:11

The click/event bindings run in the context of the current data as you have found.

There are a few options to ensure that your function runs with the correct context:

  • set the correct this to a variable like self and use it in your handler (as you have mentioned)
  • use something like $.proxy or .bind in your view model to ensure that this is correct (as you have mentioned)
  • bind the function in-line like data-bind="click: $root.remove.bind($root)"
  • use an (ugly) anonymous function like data-bind="click: function() { $root.remove($data); }"
查看更多
登录 后发表回答