简体   繁体   English

将事件对象传递给kickout.js函数

[英]Passing the event object to knockout.js function

I'm using bind to call the function with parameters from my view: 我正在使用bind从我的视图中调用带有参数的函数:

<span data-bind="click: modifyByOne.bind($data, 'plus')"></span>

As per this answer I'm getting the event object by doing this: 按照这个答案,我通过执行以下操作获取event对象:

self.modifyByOne = function(type){
    var span = $(event.currentTarget);
};

In Chrome everything works ok, but in Firefox I get the following console error: 在Chrome中,一切正常,但在Firefox中,出现以下控制台错误:

event is not defined 未定义事件

How can I get it working in Firefox too? 我如何也可以在Firefox中使用它? Knockout documentation doesn't provide much answers to this. 淘汰赛文档并未对此提供太多答案。

The knockout click binding passes two arguments to the listener method: the current binding context ( $data ), and the event. 敲除单击绑定将两个参数传递给侦听器方法:当前绑定上下文( $data )和事件。

By using bind you can, like you did, specify additional arguments to pass to the method. 通过使用bind,您可以像您一样指定其他参数以传递给方法。 These arguments are passed before the two default arguments. 这些参数在两个默认参数之前传递。 Your method should therefore accept a type, data and event argument. 因此,您的方法应接受类型,数据事件参数。

self.modifyByOne = function(type, data, event){
  var span = $(event.target);
};

While this should work, it's considered bad practice to do stuff with the DOM from your code. 尽管这行得通,但对代码中的DOM进行处理被认为是不好的做法。 Try creating a custom binding instead . 尝试创建自定义绑定

You don't declare the event parameter in your function signature. 您无需在函数签名中声明event参数。 But besides that, if you need to access the actual DOM element in Knockout, you should be using a custom binding handler; 但是除此之外,如果您需要访问Knockout中的实际DOM元素,则应该使用自定义绑定处理程序。 you shouldn't be accessing the DOM from inside of your view model. 您不应该从视图模型内部访问DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM