0

I have an object:

var Person = function(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.sayHello = function() {
    console.log("Hello" + this.name + ", " + this.age);
}
var sam = new Person("Sam", 31);

I want to call Person.sayHello as onclick callback and I found out that I can do it with bind method.

$("#button").on("click", Person.sayHello.bind(sam));

Maybe there is more generic solution for it or some specific approach for jQuery to solve this problem at jQuery?

I need to add one note. I can have multiple instances of Person class and I want to make click to work for all of them. I thought about some loop over all Person instances and binding them to callback.

9
  • @vinayakj I will add it. I can create a lot of person instaces. Commented Nov 4, 2015 at 21:06
  • @vinayakj (a) that will call it immediately, instead of binding it as an event handler for later (b) it will only bind the function, without the context of the calling object. Commented Nov 4, 2015 at 21:06
  • @vinayakj then (b) still applies: codepen.io/paulroub/pen/MaqeMV (note "Hello, undefined" result) Commented Nov 4, 2015 at 21:09
  • bind() is about the best way to do it. you could use an anon+closure, but usually bind() solutions are simpler and more re-usable. Commented Nov 4, 2015 at 21:11
  • @vinayakj I thought about iterating over all Persons and put them into bind Commented Nov 4, 2015 at 21:12

1 Answer 1

1

Since you're using jQuery, you can use the jQuery.proxy() method, which is specifically made for attaching event handlers and keeps this intact. So, something like:

$('#button').on('click', $.proxy(sam, 'sayHello'));

However, if you're going to loop through a bunch on a single button click, you don't even need to worry about all that.

var sam = new Person("Sam", 31);
var bob = new Person("Bob", 32);
var pat = new Person("Pat", 33);
var people = [sam,bob,pat];
$('#button').on('click', function () {
    people.forEach(function (person) {
        person.sayHello();
    });
});

That assumes a relatively recent browser that supports Array.prototype.forEach. Basically, those People objects already know what they're doing.

If you need to support older browsers change that forEach to:

$.each(people, function (i, person) {
    person.sayHello();
});

Thanks to @dandavis for the tip.

Sign up to request clarification or add additional context in comments.

1 Comment

you can use $.each and change the callback parameters to (i, person) to ensure IE8 compat...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.