API design and jQuery [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have often heard that jQuery has made some poor API decisions. Although jQuery is not my favourite library it's the library I've used most often and I find it hard to point out specific mistakes in the API design or how it could have been improved.
What parts of jQuery's API could have been done better, how could it have been implemented different and why would that different implementation be better?
The question extends to both low level individual details of the API and high level details of the API. We are only talking about flaws in the API rather then flaws in the high level design / purpose of the library, jQuery is still a DOM manipulation library centred around a selector engine.
Because of the necessity of API freezing in popular libraries, jQuery is stuck in it's current state and the developers are doing a great job. As can be seen by the recent .attr vs .prop change the developers do not have the flexibility to change any of their design decisions (which is a shame!).
One specific example I can think of would be
$.each(function(key, val) { })
vs
$.grep(function(val, key) { })
which is confusing enough that I have to double check what the parameters are frequently.
Please do not compare the jQuery library to full fledged frameworks like dojo and YUI and complain about lack of features.

.load() is overloaded with entirely different behavior depending on the arguments passed
.toggle() is overloaded with entirely different behavior depending on the arguments passed
too much overloading of the jQuery() function perhaps.
the .attr() you mentioned. The distinction from properties should have been immediate IMO.
.map( key,val ) but $.map( val,key ), and the this values are different.
non-standard selectors ought to have been kept out of Sizzle IMO. Javascript based selector engines should become obsolete in a number of years, and people hooked on the proprietary selectors will have a more difficult transition
poor method naming of methods like .closest() or .live(). What exactly do they do?
I recently discovered that you can't set the standard width and height attributes via the props argument when creating a new element. jQuery runs its own width and height methods instead. IMO, the spec attributes should have been given priority, especially since width and height can be set via css.
$('<img/>', {
css:{width:100, height:100},
width:100, // <-- calls method, why?
height:100, // <-- calls method, why?
});
$.get() and .get() are entirely different.
.get() and .toArray() are identical when passing no arguments
toArray() and $.makeArray() do effectively the same thing. Why didn't they give them the same name like .each() and $.each()?
two different event delegation methods. .delegate() the sensible one, and .live() the magical "wow, it just works!" one.
.index() is overloaded with 3 behaviors, but their differences can be confusing
// v---get index v---from collection (siblings is implied)
$('selector').index();
// v---from collection v---get index
$('selector').index(element);
// v---get index v---from collection
$('selector').index('selector');
The first one is understandable if you remember that it only operates on the first element
The second one makes the most sense since jQuery methods usually operate on an entire collection.
The third one is entirely confusing. The method gives no indication of which selector is the collection and which selector represents the element whose index you want from the collection.
Why not just eliminate the third one, and have people use the second one like this:
// v---from collection v---get index
$('selector').index( $('selector') );
This way it fits more closely with the rest of jQuery where .index() operates on the entire collection.
Or at least reverse the meaning of the selectors to fit in better:
// v---from collection v---get index
$('selector').index('selector');
Here's another to think about anyway.
I have some concerns with jQuery's event handling/data storage system. It is praised because it doesn't add functions to on[event] properties that can close around other elements, creating memory leaks in IE. Instead it places a lightweight expando property, which maps to an entry in jQuery.cache, which holds handlers and other data.
I believe it then attaches a handler with in turn invokes the handler that you assigned. Or something like that.
Whatever the system is doesn't really matter. The point is that the connection between the element(s) and the jQuery.cache is that expando.
Why is that a big deal? Well philosophically jQuery is not a framework; it is a library. It would seem that as a library you should be able to use or not use the jQuery functions without concern for negative effects. Yet if you go outside jQuery when removing elements from the DOM, you've orphaned any handlers and other data associated with those elements via the expando, creating a nice and fully cross-browser memory leak.
So for example, something as simple as el.innerHTML = '' could be very dangerous.
Couple this with the jQuery.noConflict() feature. This enables developers to use jQuery with other libraries that utilize the $ global namespace. Well what if one of those libraries deletes some elements? Same problem. I have a feeling that the developer that needs to use a library like Prototypejs along side jQuery probably doesn't know enough JavaScript to make good design decisions, and will be subject to such a problem as I've described.
In terms of improvements within the intended philosophy of the library, as far as I know, their philosophy is "Do more, write less" or something. I think they accomplish that very well. You can write some very concise yet expressive code that will do an enormous amount of work.
While this is very good, in a way I think of it as something of a negative. You can do so much, so easily, it is very easy for beginners to write some very bad code. It would be good I think if there was a "developer build" that logged warnings of misuse of the library.
A common example is running a selector in a loop. DOM selection is very easy to do, that it seems like you can just run a selector every time you need an element, even if you just ran that selector. An improvement I think would be for the jQuery() function to log repeated uses of a selector, and give a console note that a selector can be cached.
Because jQuery is so dominant, I think it would be good if they not only made it easy to be a JavaScript/DOM programmer, but also helped you be a better one.

The way jQuery handles collections vs single elements can be confusing.
Say if we were to update some css property on a collection of elements, we could write,
$('p').css('background-color', 'blue');
The setter will update the background color of all matching elements. The getter, however, assumes that you are only interested in retrieving the value of the first element.
$('p').css('background-color')
MooTools would return an array containing the background colors of each matching element, which seems more intuitive.
The naming conventions for jQuery promote conciseness instead of clarity. I like Apple's strategy in naming things:
It's better to be clear than brief.
And here's an example of a method name from a mutable array class (NSMutableArray) in Objective-C.
removeObjectAtIndex:(..)
It's not trying to be clever about what's getting removed or where it's getting removed from. All the information you need to know is contained in the name of the method. Contrast this with most of jQuery's methods like after and insertAfter.
If somebody can intuitively figure out what after or insertAfter does without reading the docs or the source code, then that person is a genius. Unfortunately, I'm not one - and to-date, I still have to go to the documentation to figure out what the hell gets placed where when using these two methods.

patrick dw hit most of the points in his (fantastic) answer. Just to add to his collection with a few other examples.
An API is supposed to be consistent; and jQuery succeeds in a lot of areas (being very consistent for returning a jQuery object/ get value, as expected in a lot of cases). In other situations however, it doesn't do so well.
Method Names
As already pointed out by patrick; closest() is a crap method name. prev(), and next() appear to most as if they do the job prevAll() and nextAll() actually provide.
delay() confuses a lot of people: In the following example, which do you expect to happen? (what actually happens?)
$('#foo').hide().delay(2000).slideDown().text('Hello!').delay(2000).hide();
Method Arguments
A lot of the tree traversal functions are inconsistent with what they accept; they all accept a mixture of selectors, jQuery objects and elements, but none are consistent; which is bad considering they all do similar jobs. Check out closest(), find(), siblings(), parents(), parent() and compare the differences!
Internally, the "core" of jQuery originally contained lots of intertwined methods, that the dev team have struggled to split up (and done really well to), over the past releases. Internal modules such as css, attributes, manipulation and traversing all used to be bundled in the same big package.

Included in jquery:
.post()
.get()
.getScript()
.getJSON()
.load()
Not in jQuery:
$.getXML();
$.headXML();
$.postXML();
$.putXML();
$.traceXML();
$.deleteXML();
$.connectXML();
$.getJSON();
$.headJSON();
$.postJSON();
$.putJSON();
$.traceJSON();
$.deleteJSON();
$.connectJSON();
$.headScript();
$.postScript();
$.putScript();
$.traceScript();
$.deleteScript();
$.connectScript();
$.getHTML();
$.headHTML();
$.postHTML();
$.putHTML();
$.traceHTML();
$.deleteHTML();
$.connectHTML();
$.getText();
$.headText();
$.postText();
$.putText();
$.traceText();
$.deleteText();
$.connectText();
$.head();
$.put();
$.trace();
$.delete();
$.connect();
Why does this bother me? Not because we don't have the above methods in the library, that's just dumb and I'd hate if we ever did (plus, most won't work with browsers), but what I hate is these short-hand methods all over the place: $.post(); Sends an ajax request via post.
Know what covers off everything in this list? The one function that isn't short-hand, $.ajax, it's full featured and covers off everything, you can even configure it to store defaults and in essence create all of these short-hands. You can create your own methods if you wish to call that call to ajax (which is what these all do).
Here's where it's really REALLY annoying.
Somebody writes all their code using shorthand:
$.getJSON(
'ajax/test.html',
function(data) {
$('.result').html(data);
}
);
Okay, oh wait, we want to change that to an XML feed we get from a post, also we need to make something happen before and after post. Oh, lets just switch to the non-short-hand method
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
Oh wait, I can't just replace the word, the whole structure is all over the place.
This, and especially for things like $.load(), cross lines into why PHP has such a hated API, they're trying to do things they shouldn't do.
To extend this beyond AJAX calls, look at the animation portion. We have calls to slideUp, slideDown, fadeIn, fadeOut, fadeToggle, show, and hide. Why? Where's my slide left, slide right, slide in, slide out, teleport, and every other thing we can think up? Why not just stick to $.animate() and let someone write a plugin if we want those effects. Infact, someone did write a plugin, jQueryUI extends animations. This is just crazy, and leads to people not knowing that some effects create CSS rules on their divs that end up goofing up what they want to do later on.
Keep it pure, keep it simple.

Related

Backbone - What is the more efficient scoped finding method for a DOM element?

I'm aware there are many ways you can do a DOM query inside a view:
$(view.el).find("#element");
$(“#element”, view.el);
view.$("#element");
Which one is the best way to go, and why?
Bakcbone keeps a reference to the the el of the view, so the last one will be the shorthand version of view.$el.find('#element');
view.$("#element"); /// is like I said is just the same that :
view.$el.find('#element');
I think this means the last one is the fastest as its only looking into the el and not in the entire DOM and still uses find.
take a look at this link. http://pivotallabs.com/shorthand-for-searching-a-view-s-dom-in-backbone/
Always use find over context selector.
" It’s true, where possible you should always try to run your selections based on a context however it’s useful just to bare in mind that when you’re passing a context to the jQuery constructor, it creates an extra unnecessary extra function call.
jQuery’s insides run content.find(selector) anyway, so you can technically skip that step if you’re working in a page structure that may not benefit greatly from using context. Below you can see an example of what I’m talking about. "
Source : 8 jQuery Performance & Optimization Tips You Need In 2010 (Tip #6)
Yes the article is old, but it is still true.
TL;DR version : Context selector call the .find() function. Using .find() directly reduce the number of call.

performance issue : storing a reference to DOM element vs using selectors

So in my app, the user can create some content inside certain div tags, and each content, or as I call them "elements" has its own object. Currently I use a function to calculate the original div tag that the element has been placed inside using jquery selectors, but I was wondering in terms of performance, wouldn't it be better to just store a reference to the div tag once the element has been created, instead of calculating it later ?
so right now I use something like this :
$('.div[value='+divID+']')
but instead I can just store the reference inside the element, when im creating the element. Would that be better for performance ?
If you have lots of these bindings it would be a good idea to store references to them. As mentioned in the comments, variable lookups are much much faster than looking things up in the DOM - especially with your current approach. jQuery selectors are slower than the pure DOM alternatives, and that particular selector will be very slow.
Here is a test based on the one by epascarello showing the difference between jQuery, DOM2 methods, and references: http://jsperf.com/test-reference-vs-lookup/2. The variable assignment is super fast as expected. Also, the DOM methods beat jQuery by an equally large margin. Note, that this is with Yahoo's home page as an example.
Another consideration is the size and complexity of the DOM. As this increases, the reference caching method becomes more favourable still.
A local variable will be super fast compared to looking it up each time. Test to prove it.
jQuery is a function that builds and returns an object. That part isn't super expensive but actual DOM lookups do involve a fair bit of work. Overhead isn't that high for a simple query that matches an existing DOM method like getElementById or getElementsByClassName (doesn't in exist in IE8 so it's really slow there) but yes the difference is between work (building an object that wraps a DOM access method) and almost no work (referencing an existing object). Always cache your selector results if you plan on reusing them.
Also, the xpath stuff that you're using can be really expensive in some browsers so yes, I would definitely cache that.
Stuff to watch out for:
Long series of JQ params without IDs
Selector with only a class in IE8 or less (add the tag name e.g. 'div.someClass') for a drastic improvement - IE8 and below has to hit every piece of HTML at the interpreter level rather than using a speedy native method when you only use the class
xpath-style queries (a lot of newer browsers probably handle these okay)
When writing selectors consider how much markup has to be looked at to get to it. If you know you only want divs of a certain class inside a certain ID, do one of these $('#theID div.someClass') rather than just $('div.someClass');
But regardless, just on the principle of work avoidance, cache the value if you're going to use it twice or more. And avoid haranguing the DOM with repeated requests as much as you can.
looking up an element by ID is super fast. i am not 100% sure i understand your other approach, but i doubt it would be any better than a simple lookup of an element by its id, browsers know how to this task best. from what you've explained I can't see how your approach would be any faster.

When to use Vanilla JavaScript vs. jQuery?

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.
A specific example
$(this) vs this
Inside a click event referencing the clicked objects id
jQuery
$(this).attr("id");
Javascript
this.id;
Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)
EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.
this.id (as you know)
this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
this.className to get or set an entire "class" property
this.selectedIndex against a <select> to get the selected index
this.options against a <select> to get a list of <option> elements
this.text against an <option> to get its text content
this.rows against a <table> to get a collection of <tr> elements
this.cells against a <tr> to get its cells (td & th)
this.parentNode to get a direct parent
this.checked to get the checked state of a checkbox Thanks #Tim Down
this.selected to get the selected state of an option Thanks #Tim Down
this.disabled to get the disabled state of an input Thanks #Tim Down
this.readOnly to get the readOnly state of an input Thanks #Tim Down
this.href against an <a> element to get its href
this.hostname against an <a> element to get the domain of its href
this.pathname against an <a> element to get the path of its href
this.search against an <a> element to get the querystring of its href
this.src against an element where it is valid to have a src
...I think you get the idea.
There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.
In general you can replace:
$(el).attr('someName');
with:
Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.
The sentences below sort of covered it. See this answer for a better treatment.
el.getAttribute('someName');
...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.
Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:
$('span').unwrap(); // unwrap all span elements
But if there are many, you may want to do a little native DOM API:
var spans = document.getElementsByTagName('span');
while( spans[0] ) {
var parent = spans[0].parentNode;
while( spans[0].firstChild ) {
parent.insertBefore( spans[0].firstChild, spans[0]);
}
parent.removeChild( spans[0] );
}
This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.
It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.
The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.
The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.
Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.
-- Edited to encompass comments --
As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.
In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.
There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)
So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.
Vanilla JS is a fast, lightweight, cross-platform framework for
building incredible, powerful JavaScript applications.
On their homepage there's some perf comparisons:
There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:
http://www.quirksmode.org/compatibility.html
It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.
When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.
Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.
PS: PPK (the author of the site) also has a very nice book that I do recommend reading
When:
you know that there is unflinching cross-browser support for what you are doing, and
it is not significantly more code to type, and
it is not significantly less readable, and
you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:
use JavaScript. Otherwise use jQuery (if you can).
Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.
Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:
$(this).attr('id');
Is both slower and (in my opinion) less readable than:
this.id.
It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).
Are there any other common practices
like this? Where certain Javascript
operations could be accomplished
easier, without bringing jQuery into
the mix. Or is this a rare case? (of a
jQuery "shortcut" actually requiring
more code)
I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).
Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.
Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.
If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).
It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:
// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });
// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });
// poor
$('.something').load('url');
$('.something').show();
// excellent
var something = $('#container').children('p.something');
something.load('url').show();
I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.
This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.
But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.
Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.
The first answer's live properties list of this as a DOM element is quite complete.
You may find also interesting to know some others.
When this is the document :
this.forms to get an HTMLCollection of the current document forms,
this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
this.images to get an HTMLCollection of all the HTMLImageElements
and the same with the deprecated applets as this.applets
When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.
When this is a form :
this[inputNameOrId] to get the so named or identified field
When this is form field:
this.type to get the field type
When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.
As usual I'm coming late to this party.
It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.
It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.
I guess this sort of falls under the cross browser support/abstraction argument.
And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.
Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?
But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.
That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.
Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.
In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.
Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.
$(this) is different to this :
By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

Is it a bad practice to reference Javascript objects from DOM elements?

As a "best practice" for front-end developers, is it bad to use the "control" property to reference back to the Javascript object?
Here's a link to the property in question:
https://developer.mozilla.org/en/XUL/Property/control
I've seen a lot of Javascript functions that reference DOM elements using selectors and then perform DOM manipulation that way. But what if we started by traversing through the DOM tree and we have the DOM element first?
EDIT 1
Okay, it seems like there are some interest here but no contributions for some reason. This started as a conversation between me and my co-worker. He was concerned about circular references and possible cases of losing references... does that apply here? I thought as long as we don't call delete <javascript object> then we're fine.
EDIT 2 I found this: JQuery methods and DOM properties
In my world right now, I'm using the Microsoft AJAX Library where we created multiple ScriptControls and put them on various pages; which in turn, (the ScriptControls) get "modified" by page's events and sometimes events of other ScriptControls. When pages need to do something with the DOM element, the Javascript would use the respective Javascript Object's methods.
However, it seems in JQuery (based on the other question), it's common to get the DOM element then use .get(0) to grab the JQuery object out of it (if it exists).
So I guess this is a witch hunt so far and there's still no right answer to my question :(
I know I'm still lacking an example but I'm not sure how to approach this.
I am not too sure what exactly you're referring to. Could you provide a simple code example? Otherwise, your question is a bit vague IMHO. I'll give it a shot anyways:
I do not understand why there would be any lost or circular references. The control attribute is just the id (string) of the "controlling" DOM Element, not a reference to the actual DOM Element. If you delete label.control it will no longer be associated with the other DOM Element.

jQuery: what is it "forbidden" to do in plain Javascript

A jQuery best practices question.
I am writing a very jQuery intensive web page. I am new to jQuery and notice its power, but as I come with heavy javascript experience and knowledge, my question is: What should be done in jQuery and what in plain javascript.
For example, there are callbacks that send a plain DOM object as an argument. Should I use that or should I wrap it ( like $(this)).
Does it matter if I do this.x=y or $(this).attr("x", y).
If your function receives a DOM object and you don't need any jQuery functionality for that DOM object, then there is no need to make convert it to a jQuery object. For instance, if you receive a checkbox object, you can examine the checked property without any use of jQuery.
However, if you need to navigate to a different element from that checkbox, it might be worthwhile to convert it:
function yourCallback(cb) {
cb = $(cb);
var sel = $(cb).closest('td').next().find('select');
// For example, update the options in a neighboring select field
...
}
jQuery (as do other libraries) blend in smoothly with native JS. If you need extra functionality, augment the object in question.
As for your last question: You might find the data function useful to avoid nonstandard DOM attributes. If your property x in your question is in fact a valid DOM attribute, you can write either this.x = y or $(this).attr('x', y), IMO it does not matter much. However, if x is not a DOM attribute, use
$(this).data('key', value)
That way, you can store arbitrary key-value pairs with the DOM element, where value can be an arbitrary primitive value or object.
I think it's a judgement call. Use your common sense.
For instance, if you have 1000 div's on the page, you probably wouldn't want to wrap it inside $(..)
$('div').click(function() {
this.id = Random.guid(); // instead of $(this).attr('id', Random.guid());
});
As for other assignments, as long as you understand what jQuery is doing, you can stick with it just for consistency, but be aware of performance issues like in the above example.
As #colinmarc mentions, at times jQuery blurs the distinction between element attributes and object properties which can be misleading and buggy.
When your using jQuery, it always returns an instance of jQuery unless obv your using a function like val();
the reason we use $(this).value instead of this.value is to make sure that this is an instance of jQuery.
if somewhere in your code you set a variable called my_link witch is equal a DOM Object and not a jQuery function.. further in your application my_link.val() would result into an error, but by doing $(my_link).val() will assure you that the function val will be available. as $() returns an instance of jquery.
Sorry for the miss understanding in my previous post.
Since jQuery objects have richer functionality than nature JS DOM nodes, if you're on the fence, you might as well wrap in jQuery. JQuery is so lightweight, there's not really much reason not to use jQuery objects.
Does it matter if I do this.x=y or $(this).attr("x", y).
The native will be slightly faster, but you'll probably spend more time in other code-- DOM traversal or building. In this specific example, the former is more concise, so I'd choose that. Since jQuery is so lightweight, I tend to switch back and forth fluidly.
Here are other guidelines we follow:
For callbacks, like a click handler, you'll need to follow the API-- usually a DOM node. Code you write that is similar should probably just take DOM nodes as well. But if you have a list of items, always use a jQuery object.
For most code, I try to see if you can structure the code as a jQuery plugin-- applying some transformation to a set of DOM nodes. If you can do that, you'll gain some guidance from the plugin architecture.
I use jQuery's bind/trigger mechanism as it is quite flexible and low-coupling.
To keep code straight, I'd recommend name prefixing jQuery objects with a dollar sign. For example, var $this = $(this);. Although it's really no big deal to call $() excessively, it does end up looking a sloppy if you call it too much.
Hope this helps.

Categories