homepage Welcome to WebmasterWorld Guest from 54.205.247.203
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
One element, multiple events
Rain_Lover




msg:4681056
 2:45 am on Jun 19, 2014 (gmt 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?

 

Fotiman




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

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




msg:4681074
 5:30 am on Jun 19, 2014 (gmt 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".

Fotiman




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

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved