Created
October 19, 2011 19:31
-
-
Save shamansir/1299405 to your computer and use it in GitHub Desktop.
How to implement JQuery-like class in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to make JQuery-like function in Java | |
// shamansir.github.com (c) | |
public interface ProvidesElements { | |
public Elements[] get(); | |
} | |
public class JQ implements ProvidesElements { | |
. . . | |
public static JQ do(ProvidesElements elements) { | |
instance.elements = elements.get(); | |
return instance; | |
} | |
public static ProvidesElements query(String query) { | |
return do(new Selector(query)); | |
} | |
public JQ each(Callback callback) { | |
for (Element elm: this.elements) { | |
callback(elm); | |
} | |
return this; | |
} | |
public JQ css(String attr, String value) { | |
for (Element elm: this.elements) { | |
elm.getStyle().setAttribute(attr, value); | |
} | |
return this; | |
} | |
public JQ prev() { | |
return instance.findPrev(); // over this.elements | |
} | |
public Value val() { | |
return extractValue(this.elements); | |
} | |
public Element[] get() { | |
return this.elements; | |
} | |
. . . | |
public class Selector implements ProvidesElements { | |
public Selector(String query) { .... } | |
public Element[] get() { return Document.query(this.query) } | |
} | |
public class ElementsArray extends ArrayList<Element> implements ProvidesElements { | |
public Element[] get() { return asArray(); }; | |
} | |
public class Element implements ProvidesElements { | |
private final ArrayList<Element> = new ArrayList<Element>(1); | |
public Element[] get() { list.clear(); list.add(this); return list; }; | |
} | |
public class Html implements ProvidesElements { | |
public Html(String html) { .... } | |
public Element[] get() { return parseHtml(html); }; | |
} | |
} | |
// Usage: | |
JQ.do(new Selector("a :first")).each(...).css(...).prev()... | |
JQ.do(new Html("<span>foo</span>")).each(...).css(...)... | |
JQ.do(JQ.query(".class")).each(...).css(...).val() | |
// Conforming to: http://api.jquery.com/jQuery/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment