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

javascript - Bind with addEventListener - Stack Overflow

programmeradmin0浏览0评论

When using bind() on an Event Listener in JavaScript I can no longer get the element with "this".

Here is my code:

function callback(){

     console.log(this.someVar);
     // Works fine

     console.log(this);
     // No longer refers to the element, outputs "Object"

}

callback = callback.bind({someVar: 1234});

element.addEventListener('click', callback);

Any idea on how to fix this?

When using bind() on an Event Listener in JavaScript I can no longer get the element with "this".

Here is my code:

function callback(){

     console.log(this.someVar);
     // Works fine

     console.log(this);
     // No longer refers to the element, outputs "Object"

}

callback = callback.bind({someVar: 1234});

element.addEventListener('click', callback);

Any idea on how to fix this?

Share Improve this question edited Nov 2, 2019 at 21:37 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 2, 2019 at 20:56 OodOod 1,8054 gold badges27 silver badges50 bronze badges 12
  • 3 That is what bind does - it sets the this context permanently. If you don't want this behaviour, then perhaps you shouldn't use bind. – VLAZ Commented Nov 2, 2019 at 21:00
  • What output are you getting? – Kalesh Kaladharan Commented Nov 2, 2019 at 21:00
  • @VLAZ what can I use as an alternative? – Ood Commented Nov 2, 2019 at 21:02
  • @KaleshKaladharan "Object" – Ood Commented Nov 2, 2019 at 21:03
  • 2 @VLAZ I want to pass a variable to the function in the event but this variable is constantly changing. When the event fires I want the function to output the value of the variable from the time the EventListener was created. – Ood Commented Nov 2, 2019 at 21:10
 |  Show 7 more ments

4 Answers 4

Reset to default 2

If you want to pass one variable but keep the this context, then you can use currying or partial application:

Curry

Your function has to receive a value and return another function. This way you can do the following:

function callback(num) {
  return function() {
    console.log(num);
    console.log(this.id);
  }
}

var number = 1;

document.getElementById("hello").addEventListener("click", callback(number));

//change the variable
number = 2;
document.getElementById("world").addEventListener("click", callback(number));

//change the variable again
number = 3;
<button id="hello">Hello</button>
<button id="world">World</button>

Partial application

Same idea but instead of having your callback return a new function, it will just take a single argument and work normally, you need another function that will do the partial application:

function callback(num) {
  console.log(num);
  console.log(this.id);
}

var number = 1;

document.getElementById("hello").addEventListener("click", partial(callback, number));

//change the variable
number = 2;
document.getElementById("world").addEventListener("click", partial(callback, number));

//change the variable again
number = 3;


function partial(fn, arg) {
  return function() {
    return fn.call(this, arg);
  }
}
<button id="hello">Hello</button>
<button id="world">World</button>

The partial application function can be generalised to handle any amount or arguments

In ES6:

function partial(fn, ...args) {
  return function(...otherArgs) {
    return fn.apply(this, [...args, ...otherArgs]);
  }
}

In ES5:

function partial(fn) {
  var args = [].prototype.slice.call(arguments, 1);
  return function() {
    var otherArgs = [].[].prototype.slice.call(arguments);
    return fn.apply(this, args.concat(otherArgs));
  }
}

The bind() method creates a new function that, when called, has its this keyword set to the provided value.

So, when you call a function like

callback = callback.bind({someVar:1234})

this inside the function callback will be the object {someVar:1234}

To access someVar in the callback function, you have to use this.someVar.

I hope this helps.

If you are still unclear refer this article https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind


You can still use event.target and can get access to the clicked element.

function callback(event){

 console.log(this.someVar);
 // Works fine

 console.log(event.target);
 // No longer refers to the element, outputs "Object"

}

callback = callback.bind({someVar: 1234});

element.addEventListener('click', callback);

You can call bind() only once. After bind() called, this reference is bind to the argument. So the even can not be assigned to this. For example:

function f() {return this;}
f = f.bind({a:1});
f(); // => {a:1}
f = f.bind({a:2}); // this is what addEventListener actually do as if it bind this to even
f(); // {a:1}

addEventListener cannot bind this again.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>