The product of a web developer with a little too much caffeine

Archive for July 8th, 2009

jLinq (LINQ for JSON) Screencast #2 – Creating Your Own Extension Methods

with one comment

jLinq is a Javascript library that allows you to do LINQ style queries with JSON data.

Did you know that jLinq let’s 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 a extension method looks like.

    name:"evenValues", //the name of this method
    type:"query", //the kind of method this is
    count:0, //how many parameters we expect
    method:function(query) {	

        //determine how to evaluate the value being compared
        var compare = query.when({
            "string":function() {
                return query.value.length;
            "array":function() {
                return query.value.length;
            "other":function() {
                return query.helper.getNumericValue(query.value);
        //the actual comparison
        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…

//this method is one way to do it
    .less("age", 30)

//this method was generated automatically - saves us a step!
    .less("age", 30)

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.

Watch Screencast #2 – Extending A Method In jLinq


Written by hugoware

July 8, 2009 at 6:26 am