mbest / knockout-repeat

REPEAT binding for Knockout
http://mbest.github.io/knockout-repeat/
131 stars 18 forks source link

Virtual element points to the previous virtual element used #17

Closed JorgeMCSilva closed 10 years ago

JorgeMCSilva commented 10 years ago

Hey,

Here is what I have (maybe I did something wrong).

<div data-bind="repeat:{ foreach: projects, index:'$projIndex', item:'$projItem' }">
    <table>
        <thead>
            ...
        </thead>
        <tbody>
            <tr data-bind="repeat:{ foreach: $projItem().fte, item: '$fteItem', index:'$fteIndex' }" data-repeat-bind="visible:$root.fteVisible($projItem())">
                <td>
                    <a data-bind="visible:$root.isDeleteVisible($fteItem()),click:$root.removeFTEFromProject.bind($fteItem(),$fteIndex)" title="Remove"></a>
                    <span data-bind="text:$fteItem().code"></span>
                </td>
            </tr>
        </tbody>
    </table>
</div>

My problem resides on the 'a' element. $root.isDeleteVisible($fteItem()) - this call is totally fine and returns the correct context.

$root.removeFTEFromProject.bind($fteItem(),$fteIndex) - this one returns me the $root model instead of the item like the previous.

I can change it to $root.removeFTEFromProject alone and I will still get the $root model. My current workaround is to do a ko.contextFor(event.currentTarget).$fteItem() and then I can continue with what I was doing.

If i put an inline comment with the 'div' repeat, the second repeat will instead point to the $projItem instead.

<!-- ko foreach: {data: projects, as: '$projItem'} -->
    <table>
        <thead>
            ...
        </thead>
        <tbody>
            <tr data-bind="repeat:{ foreach: $projItem().fte, item: '$fteItem', index:'$fteIndex' }" data-repeat-bind="visible:$root.fteVisible($projItem())">
                <td>
                    <a data-bind="visible:$root.isDeleteVisible($fteItem()),click:$root.removeFTEFromProject.bind($projItem(),$fteIndex)" title="Remove"></a>
                    <span data-bind="text:$fteItem().code"></span>
                </td>
            </tr>
        </tbody>
    </table>

I am using KO 3.1

UPDATE:

I just noticed that if I have the binding like: click:$root.removeFTEFromProject.bind(-1,$projItem(),$fteIndex) Now everything is working and sending the following signature:

function removeFTEFromProject(projItem, fteIndex, rootModel, event){}

My question is why is the 1st element ("-1") being discarded every time?

Cheers, J

mbest commented 10 years ago

The first parameter to bind is the value that will become this in the function. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)

Generally you'll want this to be the owner object, so you would use bind as follows:

click: $root.removeFTEFromProject.bind($root, $projItem(), $fteIndex)