jLinq is a Javascript library that allows you to do LINQ style queries with JSON data.
Did you know that jLinq lets you extend the base library with your own methods? Did you realize that any method you create plugs right in and works with the built in jLinq features?
This screencast goes over some of the basics to creating your first extension method for jLinq.
Creating a Query Method
A Query
method is what determines what records stay and which records are removed from a jLinq query. Here is a sample of what an extension method looks like:
jLinq.extend({
name:"evenValues",
type:"query",
count:0,
method:function(query) {
var compare = query.when({
"string":function() {
return query.value.length;
},
"array":function() {
return query.value.length;
},
"other":function() {
return query.helper.getNumericValue(query.value);
}
});
return compare % 2 == 0;
}
});
You’ll notice we provide the name of this new method, the kind of method (in this instance, a query
method), the expected number of parameters (not counting the field name) and then the actual method we use to determine if we keep the record.
If you don’t understand how this works exactly, then you might want to watch the screencast at the end of this post to see how this works step by step.
Operator Naming
This screencast also explains operator naming. When you extend a query
method, several additional operator prefixed name methods are added to jLinq as well. Each of these perform the correct switches when they are used. For example…
jLinq.from(data.users)
.less("age", 30)
.or()
.evenValues()
.select();
jLinq.from(data.users)
.less("age", 30)
.orEvenValues()
.select();
Of course, if you name your method something like orHasSomeValue()
you’re going to end up with some strangely named operator methods (for example orOrHasSomeValue()
).
It’s Simple–ish
Extension methods are a little confusing at first but after you create your first one, you should be on your way. This screencast will get you started in that direction.