Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #25847

Use of bind()

Newsgroups comp.lang.javascript
Date 2014-09-13 15:19 -0700
Message-ID <df48d594-cbac-4e87-8622-e70c1d6d915d@googlegroups.com> (permalink)
Subject Use of bind()
From enrique.melero@gmail.com

Show all headers | View raw


Hello, I am reading the book Programming JavaScript Applications and I find an example of use of bind() that is not supposed to work, to ilustrate what bind() does. Well I didnt quite get it so I tried to reproduce the error to understand what it really does, but to my surprise it runs with no problem.

This is the fiddle http://jsfiddle.net/quiquee/20cnkfba/1/

The book says:

Let's take a look at a common use case for .bind()--an event handler:

var lightbulb = {
    toggle: function toggle() {
      this.isOn = !this.isOn;
      return this.isOn;
    },
    isOn: false
  },
  toggle = lightbulb.toggle,
  lightswitch = document.getElementById('lightswitch');

lightswitch = document.getElementById('lightswitch');
lightswitch.addEventListener('click',
  lightbulb.toggle, false);

Glancing over this code, it looks simple enough. An event listener gets attached to the lightswitch DOM with .addEventListener(). There's just one problem: this code will fail because the context inside an event listener is not the object that the method was assigned to at design time. Instead, it's a reference to the element that was clicked.

Even after you click the switch element, lightbulb.isOn will be false. You can fix this mess with .bind(). You only need to alter the toggle assignment:

toggle = lightbulb.toggle.bind(lightbulb);

Well, as you can see I didn't add that and the code works. If someone can explain or give me a correct example so I can understand what bind() does.

Thanks

Back to comp.lang.javascript | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Use of bind() enrique.melero@gmail.com - 2014-09-13 15:19 -0700
  Re: Use of bind() Ben Bacarisse <ben.usenet@bsb.me.uk> - 2014-09-14 01:01 +0100
    Re: Use of bind() Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2014-09-14 11:48 +0200
  Re: Use of bind() JJ <jj4public@vfemail.net> - 2014-09-14 11:01 +0700
    Re: Use of bind() enrique.melero@gmail.com - 2014-09-14 00:54 -0700

csiph-web