Linq.js scoping

233 views Asked by At

I am stuck with the following situation. I have a select statement which uses a function in the current scope me. How do I go about putting me into the select function?

var me = this;
var results = Enumerable
              .from(jsonData) 
              .select('x,i=>{abbr:me.transform(x), name:x}')
              .toArray(); //me.transform(x) will hit error

'me' is an instance of a dynamically generated object, and me.transform(x) uses other dependencies in 'me' to work as well. That means I cannot make 'me.transform()' global function.


EDIT

var me = this;
var results = Enumerable
              .from(jsonData) 
              .select(function(x,i){
                  return {abbr:me.transform(x), name:x};
              }).toArray(); 

Actually, this modification will work, however, I would like to find out the how to make the shortcut syntax work.

2

There are 2 answers

2
brdu On

My bad. Is this what you mean?

var me = this;
var results = Enumerable
          .from(jsonData) 
          .select('x,i=>{abbr:' + me.transform(x) + ', name:x}')
          .toArray(); //me.transform(x) will hit error
0
Jeff Mercado On

What you could do is project your objects to a composite object containing both the item in the collection and the object you want to introduce into the query.

You can use this Capture function to capture the variables:

function Capture(bindings, name) {
    var benumerable = Enumerable.From(bindings),
        itemname = name || 'Item';
    return function (e) {
        return e.Select(function (item) {
            return benumerable.Concat(Enumerable.Return({ Key: itemname, Value: item }))
                .ToObject("$.Key", "$.Value");
        });
    };
}

Use it in a Let binding.

var query = Enumerable.From(data)
    .Let(Capture({ Me: me }))
    .Select("{ abbr: $.Me.transform($.Item), name: $.Item }")
    .ToArray();