Welcome to WebmasterWorld Guest from 23.22.140.143

Forum Moderators: open

Message Too Old, No Replies

One element, multiple events

     
2:45 am on Jun 19, 2014 (gmt 0)

Junior Member

5+ Year Member Top Contributors Of The Month

joined:Mar 1, 2010
posts: 194
votes: 0


In jQuery you can easily do it like this:

$("#foo").focus(function () {
// Do this.
}).blur(function () {
// Do that.
});


Can we do something similar in JavaScript so we don't have to repeat #foo in two separate functions?
3:05 am on June 19, 2014 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4966
votes: 10


That's called "method chaining". Basically, if you define your JavaScript class so that the methods return this then you should be able to do chaining. For example:

function foo () {
this.history = [];
}
foo.prototype.method1 = function () {
this.history.push('method1');
return this;
}
foo.prototype.method2 = function () {
this.history.push('method2');
return this;
}
foo.prototype.logHistory = function () {
console.log(this.history);
return this;
}
var bar = new foo().method1().method2().logHistory().method2().logHistory();
5:30 am on June 19, 2014 (gmt 0)

Junior Member

5+ Year Member Top Contributors Of The Month

joined:Mar 1, 2010
posts: 194
votes: 0


That's called "method chaining".

It's new to me.

Thanks for the sample code, but it seems that using two separate functions for #foo is easier than "method chaining".
1:01 pm on June 19, 2014 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4966
votes: 10


It's really not very complicated. It's just a matter of returning the same object that you're working on. If your code is not object oriented, then method chaining wouldn't make sense. But if you have 2 methods of the same object, chaining is easy.