I want my code to be like this:
select("*").where("you='me'").and("me='him'").and("game='nes'");
I have only this:
function select(selector){
this.where = function(where){
//Do something with where and select.
//Add the method AND <---
}
}
I dont know how to add the method add in the method where.
3 Answers 3
This is sometimes called a 'fluent interface'
Simply return this from each function.
If you want to capture the "select" context, capture this in a variable within that scope and then return it when needed. This is important as this points at the function that is currently executing.
function select(s){
var that = this;
this.where = function(condition){
that.filter(condition);
return that; //this == select.where
}
this.and = function (condition) {
that.filter(condition);
return that;
}
this.end = function(){
return that.results(); // or similar depending on the consumed api of course
}
return this; // this == select
}
1 Comment
In each function, put "return this;" at the bottom. So when you call .and() it's called on "this", which is "select". Sorry on iPhone, so no formatting!
Comments
one way to do it:
function select(selector){
return {where:function(where){
//do whatever you're doing with where and selector
return {and:function(whatever){/*do something with whatever*/}}
}}
}
you can add additional functions to each returned object
Jsfiddle: http://jsfiddle.net/markasoftware/78aSa/1/
if you are trying to make it so that and and where are on the same object, do this instead:
function select(selector){
var selectObj=this;
this.where=function(where){
//do whatever with where and select
//now add the and method
selectObj.and=function(whatever){
//do stuff with selector, where, and whatever
}
return selectObj
}
return selectObj;
}
jsfiddle of this one: http://jsfiddle.net/markasoftware/34BYa/
method chaining, read a bit here: kwilson.me.uk/blog/simple-javascript-method-chaining