Accept arbitrary objects in $.qsa #321

Closed
pamelafox opened this Issue Nov 19, 2011 · 4 comments

Projects

None yet

4 participants

@pamelafox
Contributor

In my experience of porting a jQuery plugin (https://github.com/jquerytools/jquerytools/tree/master/src/dateinput) to Zepto, I discovered that it passed itself into various jQuery functions, like .add(), where itself was simply a JavaScript object. This resulted in a DOM error when Zepto processed those functions, as it tried to do a querySelectorAll on the object and failed. I fixed it by wrapping the querySelectorAll in a try/catch:

function attemptQuerySelectorAll(element, selector) {
  try {
    return slice.call(element.querySelectorAll(selector));
  } catch(e) {
    return [selector];
  }
}

$.qsa = $$ = function(element, selector){
  var found;
  if (element === document && idSelectorRE.test(selector)) {
    found = element.getElementById(RegExp.$1);
    return found && [found] || [];
  } else if (classSelectorRE.test(selector)) {
    return slice.call(element.getElementsByClassName(RegExp.$1));
  } else if (tagSelectorRE.test(selector)) {
    return slice.call(element.getElementsByTagName(selector));
  } else {
    return attemptQuerySelectorAll(element, selector);
  }
}

It's not clear to me from the jQuery docs whether plugins are supposed to do this or not, but, well, they apparently do, so perhaps Zepto can accomodate.

@pamelafox
Contributor

Okay, it turns out this is more complicated than I originally thought, since the plugins also bind and trigger events on the non-DOM objects - so trigger, add, and remove would also need to be modified (they use addEventListener and dispatchEvent now). I've tried modifying but haven't figured out the right way to do it yet.

So maybe this is too significant of a change for now. I'm working around for now.

@mislav
Collaborator
mislav commented Nov 26, 2011

I don't even know what's going on, but I think if you construct a Zepto instance with non-DOM objects, you can't really expect DOM methods to work for it.

Also, plugins that bind and trigger their own events, especially on non-DOM objects, are simply badly written, so I don't really have great motivation to make Zepto work with them.

Let us know when you have more thoughts on this.

@ollym
Contributor
ollym commented Dec 10, 2011

I was thinking about something like this too but more along the lines of using $( { some: 'object' } ) adding a nice enumerable wrapper.

@mislav mislav was assigned Apr 5, 2012
@madrobby
Owner
madrobby commented Apr 5, 2012

In the latest master, code like this works:

$({ foo: 'bar' }).each(function(idx,item){ console.log(item.foo) })
// prints "bar"
@madrobby madrobby closed this Apr 5, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment