Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout foreach binding calling click event while iteration

I'm using knockout's foreach to draw table with clickable cells First column and table headers are used for population values inside table.

 <tbody>
        <!--ko foreach: $root.schedules -->
        <tr>
            <td data-bind="text: FromTo "></td>
            <!-- ko foreach: $root.weekdays -->
            <td data-bind="css:{selected:$root.objectForEdit().isSelected(id, $parent.Id) }, click: $root.changeEditObj(id, $parent.Id), with: $root.getDetailsModel(id, $parent.Id)">
                <span data-bind="text: lesson"></span>
            </td>
            <!-- /ko -->
        </tr>
        <!--/ko-->
    </tbody>

As it can be seen from code snippet I'm using some css binding and also binding modal pop-up dialog to cell click event.

Table is drawn as expected, everything is working fine, but first time when form loads my modal form is poping up even there is no cell click happening. I've tried to figure out why this happening and found that inside iteration knockout is not only binding click event but calling click event's handler function (which is showing pop-up) as well.

I'm assuming problem is with knockout binding. Is there any solutions for this problem? How can I avoid function call inside foreach iteration ?

like image 228
Izzatkhon Shamiev Avatar asked Aug 17 '15 09:08

Izzatkhon Shamiev


1 Answers

Thanks Chaim. I accidentally deleted his answer.

I've changed

click: $root.changeEditObj(id, $parent.Id)

to

click: $root.changeEditObj.bind(this, id, $parent.Id)

and it solved the problem.

This also worked fine:

click: function{$root.changeEditObj(id, $parent.Id)}

Additional Information on this can be found here

like image 122
Izzatkhon Shamiev Avatar answered Nov 14 '22 21:11

Izzatkhon Shamiev