【问题标题】:Pass an event object to a function by code通过代码将事件对象传递给函数
【发布时间】:2013-10-30 18:10:26
【问题描述】:

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

本质上,我知道我可以这样做来调用我的函数(用 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 示例手动(通过代码)触发事情?只是感觉像个黑客,仅此而已。

谢谢。

【问题讨论】:

  • 您需要事件对象的哪一部分?也许你可以使用类似updateThisValue({target: <DOMNode>})
  • updateThisValue 会对事件对象做什么?由于 Javascript 是一种动态语言,您可以传递任何对象,只要它“看起来”像一个 jQuery 事件对象,关于所访问的属性和函数。 (en.wikipedia.org/wiki/Duck_typing)

标签: javascript function events backbone.js


【解决方案1】:

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

所以你可以这样做:

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) 的唯一原因是,如果您想在updateThisValue 函数中使用对this 的引用(这将引用到处理该事件的这个dom节点)。如果您不需要在 updateThisValue 中引用 this,那么您可以轻松地执行以下操作:

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

【讨论】:

    【解决方案2】:

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

    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);
    });
    

    【讨论】:

    • 啊,你真是个天才。这正是我应该做的。我对整个 MVC 结构有点陌生,并且继承了这个相当复杂、部分纠缠不清的 JavaScript 代码来更新。谢谢,迈克。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多