在页面加载时调用 Knockout JS 鼠标悬停事件

Knockout JS mouseover event being called on pageload

我通过敲除将鼠标悬停事件附加到一堆输入。由于输入位于 ko foreach 块中,因此正在创建大量输入,并且在页面加载时,会为页面上添加的每个输入调用 mouseover 事件。这使我的页面加载非常缓慢。知道为什么在页面加载时调用该事件吗?

<!-- ko foreach: FilteredForecasts -->
     <td>
          <input class="tiny" type="number" min="0" max="80" data-bind="disable: Elapsed() || (!$parent.ResourceId() || $parent.EditingName()), value: Hours, css: { 'pending': Pending, 'saved': !Pending() && Hours() && !Elapsed(), 'highlighted': Highlighted, 'elapsed': Elapsed }, attr: { id: 'h_' + $index(), title: (!$parent.ResourceId() || $parent.EditingName() ? 'You must first save a resource to enter hours.' : TotalHoursString()) }, event: { mouseover: UpdateTotalHours($parent.ResourceId()) }" />
     </td>
<!-- /ko -->

self.UpdateTotalHours = function (resourceId) {
    if ((resourceId != null && resourceId != undefined) && self.Week() && self.Year() && (self.TotalHours() === null || self.TotalHours() === undefined)) {
        alert('here');
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf8',
            url: staffingUtilities.baseUrl + 'Forecasting/GetResourceTotalUsage/',
            data: JSON.stringify({
                id: resourceId,
                year: self.Year(),
                week: self.Week()
            }),
            success: function (data) {
                if (data == 0) {
                    self.TotalHours(null);
                    return;
                }

                self.TotalHours(data);
            }
        });
    }
};

您需要将您的鼠标悬停调用包装在一个函数中,当您的对象被绑定时,父类会导致执行 UpdateTotalHours:

mouseover: function(){ UpdateTotalHours($parent.ResourceId()); }

参见:http://knockoutjs.com/documentation/event-binding.html