How to access context given in query from inside plugin? - javascript

It's possible to do the following:
$(selector, context)
But how does $.fn.pluginX find out what what the given context was? For example:
$(selector, context).pluginX()
I've a case where a third party plugin assumes the window / document is the current one.
Edit:
I made the assumption that a document is meant by "context", but it's not always a document I guess. In my case, I'm doing cross-document stuff like $(sel, iframe.contentDocument).pluginX() and I want to make sure that if the plugin does $('body').append, then it should do $('body', theSameDocumentContext).append. Hope that helps.

jQuery element has a .context attribute. You can use it inside your plugin :
$.fn.pluginX = function(){
console.log(this.context);
}
But this is not reliable, there is too much variant. The value of context will always be document except if you pass an HTMLElement (like that):
$('p', document.getElementsByTagName('div')[0]);
But you can pass different context :
//All working :
$('p', document.getElementsByTagName('div'));
$('p', document.querySelector('div'));
$('p', document.querySelectorAll('div'));
$('p', document.getElementByID('id'));
$('p', 'div');
$('p', $('div'));
$('p', $('div').add('p'));
///... ran out of ideas
Now, it is important to know that passing a context is exactly the same has doing .find() :
$('p', 'div') === $('div').find('p');
Also, jQuery always store the previous jQuery object when chaining. If it is the initial call (no traversal method used), the previous object will be the document.
Knowing that information, if you want to get the "real" context, you can get that last element. jQuery have the property .prevObject. Use it :
$.fn.pluginX = function(){
console.log(this.prevObject);
}

$(selector, context) is same as $('context selector') and you can get it through this.selector, however this could be tricky for chained selectors.
for example:
$('.articles', '.section').pluginX()
//within the pluginX plugin function definition you can call this.selector
$.fn.pluginX = function(){
...
//this.selector = '.section .articles';
//this.selector.split(' ')[0] = '.section' //scope
...
}
But the above calculation will fail, if we have
$('.articles .writer', '.section').pluginX();
or
$('.writer', '.section .articles').pluginX();
If you have some presumption about either selector or context then it may help you to draft a logic. Let me know that helps you, or you could elaborate your specific requirement and we can try find a solution.

Related

what is prevObject and context in pushstack in jquery ?

I understand how the pushstack function works and I also understand how to use it for my plugins (I guess that's what its most used for , just for internal use and for end() to function properly and other similar methods) .
now below is the jquery source of pushstack , have a look :
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
theres a lot going on in that function really and I kind of get most part of it , but I have a small problem , understanding the below lines of code :-
ret.prevObject = this;
ret.context = this.context;
what is prevObject and context ? can somebody give me a clue , it definitely does't seem to be a javascript thing ?
Basically prevObject is used to allow flexibility for the jquery selectors chaining syntax.
Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack
Everytime you make a new filter a new jquery instance is constructed matching your selector and the previous one is stored in it to allow the .end() and the addBack() functions to work (most of the DOM transversal functions use pushStack internally). If this property were not used every selector will forget about the previous one and it will not behave like a stack. Think parent instead of prevObject and it will make it easier to understand.
The context property is deprecated in jQuery 1.10 and only used for supporting live() method but it must be added because the returning object is constructed merging an empty jQuery constructor as first parameter and a set of elements as the second.
var ret = jQuery.merge( this.constructor(), elems );
Because .merge returns the first array modified it's context property might not have the correct value so is overwritten with the correct one this.context
Check this jsfiddle and open the console. You will see that the first value of prevObject is the document as we are making a new selector and then is the ul element since we filter using find. Moreover you can go to the last filter and lookup the whole chain of selectors up to the document again.
I recommend you to use the JQuery API instead of this property as reference in production but this will allow you for example to know the result of all the selectors that have been applied to obtain a given set of DOM elements.

Using javascript "this" for jquery selector

In this code, we can obtain value of element id as 2 differnt way and both way return resultat
$("#my_div").on("click", function () {
alert( $(this).attr("id") );
alert( this.id );
});
But i interest, second way, is it proper in this case? I ask this, because in code we use jquery selector and for jquery selector, write clear javascript: this is justified and will it work always? or may be better use jquery $(this) for jquery selector? or not differnce?
this.id will give you the internal DOM element property while $(this).attr("id") returns the value of 'id' attribute.
The alternative to this.id in jQuery is using prop() method: $(this).prop("id"). However, using pure this.id construction will be easier and faster.
The main jQuery constructor can take a number of different types of argument.
In that context, this is not a selector, it is an HTMLElementNode (which jQuery calls an element).
This is perfectly OK and documented.
There is no need to spend the resources in wrapping an element in a jQuery object if you are just going to grab its ID. There aren't any compatibility problems between browsers for that.
Grabbing the id property of an HTMLElementNode takes less code and is faster then wrapping the whole thing in jQuery.
Yes, your second way is proper.
$("#my_div").on("click", function () {
// this is available within this function
alert( this.id );
});
this refers to an HTMLDOMElement within the function, and wrapping that this within $() will give you an jQuery object.
If you define another function within the click handler. Ex:
$("#my_div").on("click", function () {
// keep reference of this
var that = this;
function test() {
// this will not available here directly
// instead of that you can use reference
alert(that.id);
}
});
And $(this).attr('id'), this.id or $(this).prop('id') will give you the same result.
For choosing the best method is not always clear.
In this case you want the this.id, because the other solution requires much more calls behind the scenes (obvious calls to jQuery and attr).
If you need more information that mite differ from browser, you want the jQuery way.

Determining what the selector is?

I jumped throught the different areas of jQuery source that are called when you type:
$('.foo')
or
$('#foo')
to try and determine how jQuery parses the selector ( I assumed charAt() ) but wanted to verify.
I got to here:
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
But I got kind of stuck on what
selector.nodeType
does. This reference says that a nodeType can be pretty much anything...so what exactly are they checking for?
The jQuery API breaks down the possibilities further.
In summary what is this code snippet trying to accomplish regarding the selector variable?
nodeType suggests that the object passed to the jQuery selector is a DOM node (which will generally be an element). This allows, for instance, the following construction:
$(document)
document is an object that represents the document. $(document) builds a jQuery object based on that element. The test for nodeType means that jQuery can detect whether the argument was an element, and if so simply to build the selection based on that.
You can also see this with the common construction $(this):
$('a').on('click', function() {
console.log($(this).text()); // builds a jQuery selection based on the this
// object, which is the DOM element that was
// clicked
});

Most efficient way to re-use jQuery-selected elements

I can imagine the correct answer to this based on theory, but I'm just looking for some confirmation. I'm wondering what the most efficient way to re-use a jQuery-selected element is. For example:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
vs.
myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');
I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?
Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?
You should write your code such that you limit the number of DOM traversals.
When you write something like this:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
You are finding #my_div twice, which is inefficient.
You can improve this either by assigning the result of a selector (i.e. var x = $('.something')) and manipulate the variable x, or you can chain your method calls like this:
$('#my_div').css('background','red').attr('name','Red Div');
You'll see the above code used a lot, because you're finding the element once. The css() method will apply a CSS style and return the actual result of $('#my_div'), so you can invoke another method, in this case attr().
My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.
if you're using jQuery selector (like $('#element')), then yes, you should always store your results.
if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.
One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.
I expect something like (pardon the example)
$('#myDiv')
.addClass('processing')
.find('#myInput')
.hide('slow')
.end()
.removeClass('processing')
;
to be better performance-wise than even
var $myDiv = $('#myDiv').addClass('processing');
var $myInput = $('#myDiv #myInput').hide('slow');
$myDiv.removeClass('processing');
This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.
$('a').click(function(){
var $this = $(this);
$this.addClass("clicked");
$this.attr("clicked", true);
});

$(this) OR event.target OR var input = $(this)

jQuery is currently providing me with a fun introduction to Javascript after 12 years of surviving happily without. I'm at the stage where I'm trying to learn as much as I can about optimising the code I write and, whilst I have found plenty of good reference material, there is something quite basic which is puzzling me and I have been unable to find anything about it anywhere.
When I'm attaching something to an element how should I be referring to that element within the function. For example, when attaching a function to an element's click event :
$('#a_button',$('#a_list_of_buttons')).click(function() {
// NOW WHAT'S THE BEST WAY TO REFER TO '#a_button' ?
});
I know not to keep re-selecting it like so as the browser has to search the whole DOM again from scratch to find what it's already found once :
$('#a_button').click(function() {
// I KNOW THAT THIS IS NAUGHTY
var buttonValue = $('#a_button').val();
$('#a_button').addClass('button_has_been_clicked');
});
Currently I'm using either of the following but am not entirely sure what each is actually doing :
$('#a_button').click(function() {
// USING this
var buttonValue = $(this).val();
$(this).addClass('button_has_been_clicked');
});
But is this just re-selecting like in the first "naughty" example?
$('#a_button').click(function(event) {
// USING event.target
var buttonValue = $(event.target).val();
$(event.target).addClass('button_has_been_clicked');
});
This seems like it might be better but is it efficient to refer to 'event.target' multiple times?
$('#a_button').click(function(event) {
// USING A LOCAL VARIABLE
var thisButton = $(this);
// OR SHOULD THAT BE
var thisButton = $(event.target);
var buttonValue = thisButton.val();
thisButton.addClass('button_has_been_clicked');
});
I understand the performance efficiencies of passing things to variables but I'm unsure whether or not in these situations using $(this) or $(event.target) provides me with the same efficiencies already and so by setting a new variable I'm actually doing more work that I need to.
Thank you.
this and event.target are not always the same.
this refers to the element you assigned the listener to ( in this case the '#a_button' ). event.target however is the element that actualy triggered the event, which can be a childnode of #a_button.
So $(this) is the thing you are looking for.
See reference: http://api.jquery.com/event.target/
I may be wrong, but this and event.target are both just different references to the same element.
this and event.target are not always references to the same element. But in answer to your question, var thisButton = $(this); is definitely the winner. If you were writing C# code, you would never do the following:
this.Controls[0].Controls[0].Text = "Foo";
this.Controls[0].Controls[0].Controls.Clear();
You would do this:
var control = this.Controls[0].Controls[0];
So you probably should never re-use $(this) more than once either. Althought it's trivial to convert this from a DOM element to a jQuery object, it's still an unnecessary overhead.
However, sometimes you need to gear back from optimisation to make sure your code maintains it's readability.
Another option of course is just to change what this is. This is javascript afteral:
this = $(this); // Now `this` is your jQuery object
Disclaimer: I only just tried the above and it seemed to work. Might have some issues though.
I built a little example to demonstrate how this and e.target actually work: http://jsfiddle.net/xZAVa/
In my experience i would go with the following:
$('#a_button').click(function() {
// USING this
var buttonValue = $(this).val();
$(this).addClass('button_has_been_clicked');
});
The this in the context of your click callback method is a reference to the DOM event. Since you already have a reference to the DOM object it is trival to convert it into a jQuery object since a lookup is not required.
But on a side note, if you don't need to use jQuery in your callback, then don't. You can simply get the value of the button using standard JS this.currentTarget.value.
The other examples you mentioned require a DOM lookup, and depending on the complexity of your selector can take longer. Using a id based lookup like '#a_button' will perform better than a class based looked like .myClass.

Categories