Welcome to WebmasterWorld Guest from 54.163.35.238

Forum Moderators: open

Message Too Old, No Replies

One element, multiple events

     

Rain_Lover

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

5+ Year Member Top Contributors Of The Month



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?

Fotiman

3:05 am on Jun 19, 2014 (gmt 0)

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



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();

Rain_Lover

5:30 am on Jun 19, 2014 (gmt 0)

5+ Year Member Top Contributors Of The Month



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".

Fotiman

1:01 pm on Jun 19, 2014 (gmt 0)

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



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.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month