最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing the event object to knockout.js function - Stack Overflow

programmeradmin0浏览0评论

I'm using bind to call the function with parameters from my view:

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

As per this answer I'm getting the event object by doing this:

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

In Chrome everything works ok, but in Firefox I get the following console error:

event is not defined

How can I get it working in Firefox too? Knockout documentation doesn't provide much answers to this.

I'm using bind to call the function with parameters from my view:

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

As per this answer I'm getting the event object by doing this:

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

In Chrome everything works ok, but in Firefox I get the following console error:

event is not defined

How can I get it working in Firefox too? Knockout documentation doesn't provide much answers to this.

Share Improve this question edited May 23, 2017 at 11:45 CommunityBot 11 silver badge asked Mar 10, 2016 at 16:17 AlvaroAlvaro 41.6k31 gold badges172 silver badges348 bronze badges 1
  • The code in you question uses a variable (?) named event but it's unclear where it es from. – Jeroen Commented Mar 10, 2016 at 16:23
Add a ment  | 

2 Answers 2

Reset to default 8

The knockout click binding passes two arguments to the listener method: the current binding context ($data), and the event.

By using bind you can, like you did, specify additional arguments to pass to the method. 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. Try creating a custom binding instead.

You don't declare the event parameter in your function signature. But besides that, if you need to access the actual DOM element in Knockout, you should be using a custom binding handler; you shouldn't be accessing the DOM from inside of your view model.

发布评论

评论列表(0)

  1. 暂无评论