1

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.

asked Oct 29, 2013 at 22:59
1

3 Answers 3

1

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
}
answered Oct 29, 2013 at 23:03
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah it works! I will check you but I think there is a different method, like jQuery's, but thanks, I appreciate it!
1

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!

answered Oct 29, 2013 at 23:02

Comments

0

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/

answered Oct 29, 2013 at 23:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.