Kamil T
Kamil T

Reputation: 2216

ObservableArray.push() triggers click event

I'm making a searchable list of objects (students). When I append objects to list, I also want to add click event handler, which will pass me the objects Id.

I've made an observable array:

<script>
self.studentList = ko.observableArray();

// (...) if search conditions are met, add student to array
self.studentList.push(singleStudent);

</script>

And it's html:

<tbody data-bind="foreach: studentList">
<tr>
    <td><span data-bind='text: $data.Name, click: ClickEvent($data.Id)'></span></td>
</tr>

And function which should be triggered on click:

<script>
    function ClickEvent(pId)
    {
        console.log(pId);
    }
</script>

The clicking itself works fine. The problem is, that the self.studentList.push(singleStudent) line ALSO triggers the event.

How can I add event that would be triggered ONLY if element is clicked?

Upvotes: 1

Views: 266

Answers (1)

nemesv
nemesv

Reputation: 139758

You are not correctly wired your click handler, because you haven't passed in a reference to your function but the actual executed result.

In its current form ClickEvent is executed every time when the binding is parsed, e.g. when you add a new item to your array.

To fix it you need to wrap it to an anonymous function

<td>
  <span data-bind='text: $data.Name, click: function() { ClickEvent($data.Id) }'></span>
</td>

Or you can use the bind function:

<td>
  <span data-bind='text: $data.Name, click: ClickEvent.bind($data, $data.Id)'></span>
</td>

See also in the documentation: Accessing the event object, or passing more parameters

Upvotes: 3

Related Questions