mls3590712
mls3590712

Reputation: 810

knockout.js foreach $data AND $index()?

HTML

You can see in the html I am calling editUser with two parameters. $data being the first parameter and $index() being the second. It should send the current user object in the first parameter and the index of the foreach loop as the second.

        <tbody data-bind="foreach: users">
            <tr>
                <td>
                    <div data-bind="click: $parent.editUser.bind($data, $index())" class="clickable icon black-icon big-icon icon-edit"></div>
                </td>
                <td data-bind="text: email"></td>
                <td data-bind="text: username"></td>
                <td data-bind="text: level"></td>
            </tr>
        </tbody>

Code

    appViewModel.editUser = function( user, index ){
        console.log(user);
        console.log(index);
    };

Output

0
Object{}

It completely reverses the parameters somehow. I am at a loss to explain this behavior.

Upvotes: 1

Views: 650

Answers (1)

haim770
haim770

Reputation: 49095

The first argument of bind is the function context. So, if you want to pass 2 arguments you're gonna need this:

$parent.editUser.bind($data, $data, $index())

This way, the this in your editUser function would be the current item in your foreach iteration.

See MDN

Upvotes: 1

Related Questions