0

我已经为我的问题寻找了很多答案,但还没有找到类似的东西。本质上,我想调用一个接受事件的函数,通常会通过单击或其他事件将其附加到元素,但只是直接调用它。

本质上,我知道我可以这样做来调用我的函数(用 jQuery 编写):

function updateThisValue(event) {
    ...some code...
}

jQuery('#myElement').on('click', updateThisValue);

jQuery('#myElement').trigger('click');

有没有办法直接调用该函数?

function updateThisValue(event) {
    ...some code...
}

updateThisValue(***jQuery event object here***);

对于上下文,我使用 Backbone 更新网页上的表单,并定义了一个自定义视图,该视图被定义为在特定事件上调用其方法之一 (updateThisValue)。在同一视图的不同方法中,我希望能够直接调用“updateThisValue”方法。但是,“updateThisValue”在其代码中使用事件对象。因此,如果我直接调用该方法,它会失败并出现错误。

有没有办法做到这一点?还是我只需要按照我的第一个 I-know-I-can-do-it-this-way 示例手动(通过代码)触发事情?只是感觉就像一个黑客,就是这样。

谢谢。

4

2 回答 2

1

updateThisValue如果您有 jQuery 事件对象,则只能使用jQuery 事件对象调用。

所以你可以这样做:

var updateThisValue = function(e) {
 //...
}

//The below two pieces of code are equivalent.
$('#myelement').on('click',updateThisValue);

$('#myelement').on('click',function(e) {
   updateThisValue.apply(this,[e]);
});

.apply()我在第二个代码示例中使用并且不直接执行的唯一原因updateThisValue(e)是,如果您想thisupdateThisValue函数中使用对的引用(它将引用处理该事件的这个 dom 节点)。如果您不需要对 in 的引用thisupdateThisValue那么您可以轻松地执行以下操作:

$('#myelement').on('click',function(e) {
   updateThisValue(e);
});
于 2013-10-30T18:13:59.727 回答
0

如果您发现自己需要直接调用一个方法,那么该方法可能不应该以直接处理事件的方式定义。我建议重构您的代码:

function updateThisValue(arg0, arg1, arg2, ...) {
    ... some code ...
}

function updateThisValueUsingEvent(event) {
    // do nothing except extract the necessary values from event
    updateThisValue(event.target, event.which);
}

jQuery('#myElement').on('click', updateThisValueUsingEvent);
// direct invocation:
updateThisValue($(selector)[0], 2);

从 MVC 的角度来看,您的 updateThisValue 函数是控制器的一部分。updateThisValueUsingEvent 是从视图到控制器的绑定。特别是因为它听起来像是直接处理你的模型(通过更新一个值),你应该尝试分离视图/控制器的纠缠。

您还可以updateThisValueUsingEvent在事件绑定调用中定义为内联匿名函数:

jQuery('#myElement').on('click', function(e) {
    updateThisValue(e.target, e.which);
});
于 2013-10-30T18:22:37.293 回答