Reputation: 1496
I am trying to understand is how to create call methods after a method call.
For example in jquery you have something like this:
$("blah").data("data-id");
How would I make :
blah("cow").foo("moo");
Where the mothods blah and foo just console.log(value)
?
Upvotes: 3
Views: 908
Reputation: 31055
What you're referring to is a "fluent API" (also calling "chaining"). Your functions need to return the object that has the next method you want to call on it. For example,
var obj = function(){
var self = this;
self.blah = function(v){ console.log(v); return self; };
self.foo = function(v){ console.log(v); return self; };
};
var o = new obj();
o.blah("cow").foo("moo");
See this article for more info: http://www.i-programmer.info/programming/javascript/4676-chaining-fluent-interfaces-in-javascript.html
Upvotes: 5
Reputation: 739
Return the object that contains the functions when the function is done. then you can chain them.
Here is an example from what I made a while back:
// I extend a class with a new function
HtmlObject.prototype.stop = function () {
clearInterval( this.updater );
this.animationQue = [];
this.updater = undefined;
// Then return the object that initially called the function
return this;
};
So I could use it like object.stop().nextfuntion();
Also, In JQuery the $
is simply a shortcut to a JavaScript function.
I did the same in my test, but then with _
. I must admit it is not as nifty as JQuery but:
var _ = function ( selector, context ) {
var el = new xyvLib();
// This will simply return a collection of HtmlObjects (of which you can find a snipet above)
return el.fn.select( selector, context );
};
Upvotes: 0
Reputation: 1767
You can call .foo
on the result of blah()
only when blah()
returns an object which accepts the method foo
on it.
A simple example would be like this:
function foo(value) {
console.log(value);
}
function blah(value) {
console.log(value);
return { foo: foo }
}
Upvotes: 0
Reputation: 164
The function blah has to return an object with a method foo. Here is an example:
function blah(blahArg) {
return {
foo: function (fooArg) {
console.log(blahArg, fooArg);
}
};
}
blah("cow").foo("moo");
Upvotes: 1