Alex Rivera | Logout

jquery using objects as filters

Asked 2012-04-30T00:57:38.320
14

Is there any way to have DOM elements selectable through objects?

For example I want to be able to associate objects to DOM elements like so:

var obj = { a: 1, b:2 };
$('a').click(function() { this.selectThing = obj });

And later on...

$.something(obj);

Or even better:

$('a|selectThing?=', obj);

Something like that. You can see that I want to associate an object to a DOM element in such a way that I can grab the element with the object.

I know this can be done with the filter() method, my question is if there's a more elegant way that doesn't use filter() to do this.

EDIT:

To clarify, I want to be able to use an object kind of like a selector, so I can do something similar to this $(obj) obviously that won't work, but you get the idea (I hope)

EDIT #2:

I want to be able to do something like this:

var obj = { prop: 'prop' };
$('a').bindTo(obj);
$.retreive(obj) // should equal $('a')

I don't want it to alter obj in any way though (obj should still be {prop: 'prop'} only).

Edit
Report

2 Answers

1

As I understand, you're looking for some sugar way to run multiple named searches on the DOM and have results filtered in a namespace object.

If so, I guess the following jquery extension might be helpfull to you:

$.fn.seek = function (selectors) {
  var container = this,
    found = {};

  $.each(selectors, function (name) {
    if ($.isPlainObject(selectors[name])) {
      found[name] = $(container).seek(selectors[name]);
    }
    else if ($.type(selectors[name]) === 'string') {
      found[name] = $(container).find(selectors[name]);
    }
  });

  return found;
}

And here's the example of how the above extension might be applicable to your cases:

var res = $('body').seek({
  links: 'a',
  headers: 'h1,h2,h3,h4,h5,h6'
});

$(res.links).css({ color: 'green' });
$(res.headers).css({ color: 'red' });

I hope this helps you.

answered 2012-05-07T18:43:04.500
1

Not sure if this is what you are looking for. Perhaps you could write a custom selector based on the jquery selector, which handles objects with a selector-property the way you like. A selectable object would look like

var objSelector = {'selector' : '#select-me', 'a' : 'somestring', 'b' : 1243}; 

So you are free to use it like any other object, but you have to add the selector property. Than you add your custom selector:

$$ = (function($) {
    return function(el, tag) {
        if (typeof el === 'object' && el.selector !== undefined) {
            return $(el.selector);                  
        }
        return $(el);
    }
}($));

Now you can do things like

$$(objSelector).css({'border':'1px solid red'});

See an implementation on http://jsfiddle.net/JXcnJ/

answered 2012-05-07T18:55:48.933

Your Answer