jQuery selector vs each - javascript

Lets say I have these two pieces of code - which are identical. Also lets assume that the '.selector' returns atleast 2 objects.
Snippet 1
$('.selector').myMethod();
Snippet 2
$('.selector').each(function(){
$(this).myMethod();
});
Lets say for each one of the 'selected' returned objects I want to pass in the objects id wrapped up to myMethod().
So Snippet 2 could become
$('.selector').each(function(){
$(this).myMethod({attribute: $(this).attr('id')});
});
How can I do something similar with Snippet 1 (i.e without using $.each())?
For obvious reasons this isn't correct
$('.selector').myMethod({attribute: $(this).attr('id')});
as $(this) does not represent any one of the 'selected' returned object.
EDIT: In Snippet 1 Is there any way to reference the returned object as jQuery itself 'loops' through each returned object and calls the method. (again w/o $.each()).

The two pieces of code are not identical. One is a collection of objects and the other is a loop through a collection of objects. You can take an action on a collection that affect all equally or you can act individually on each object in the collection. Once you invoke the each() function you are individualizing objects in the collection.
To answer your question, there is no way to reference the returned collection of objects as if you were looping and applying a different function, calculation or result to each individual item in the collection.

Related

What does this code using [].filter.call do?

Iā€™m learning javascript and trying to write code that sorts a list, removing elements if they meet certain criteria.
I found this snippet that seems promising but don't have a clue how it works so I can adapt it to my needs:
list = document.getElementById("raffles-list").children; // Get a list of all open raffles on page
list = [].filter.call(list, function(j) {
if (j.getAttribute("style") === "") {
return true;
} else {
return false;
}
});
Can you guys help me learn by explaining what this code block does?
It's getting all the children of the "raffles-list" element, then returning a filtered list of those that contain an empty "style" attribute.
The first line is pretty self-evident - it just retrieves the children from the element with id "raffles-list".
The second line is a little more complicated; it's taking advantage of two things: that [], which is an empty array, is really just an object with various methods/properties on it, and that the logic on the right hand side of the equals sign needs to be evaluated before "list" gets the new value.
Uses a blank array in order to call the "filter" method
Tells the filter to use list as the array to filter, and uses function(j) to do the filtering, where j is the item in the list being tested
If the item has a style attribute that is empty, i.e. has no style applied, it returns true.
Edit:
As per OP comment, [].filter is a prototype, so essentially an object which has various properties just like everything else. In this case filter is a method - see here. Normally you just specify an anonymous function/method that does the testing, however the author here has used the .call in order to specify an arbitrary object to do the testing on. It appears this is already built into the standard filter method, so I don't know why they did it this way.
Array like objects are some of javascript objects which are similar to arrays but with differences for example they don't implement array prototypes. If you want to achieve benefits of array over them (for example like question filter children of an element )you can do it this way:
Array.prototype.functionName.call(arrayLikeObject, [arg1, [arg2 ...]]);
Here in question array like is html element collection; and it takes items without any styling.
list is assigned a collection of elements that are children of the raffles-list element
list is then reassigned by filtering its elements as follows
an empty array is filtered by calling it with the parameter list and a callback function. The formal parameters for call are this (which is the list) and optionally further objects (in this case a callback function)
The callback function receives a formal parameter j and is called for each element
If the element's value for the style attribute is empty the element is retained in the array. Otherwise it is discarded.
At the end list should contain all elements that don't have a value for its style attribute

JavaScript object key in an x length array

I wasnt quite sure what to call this question but here is what i want to do:
I am currently creating a series geneator for chartjs that will help me create my datasets.
now the way i want to do it is by simply using object keys to extract data from each element in my array.
Each element of an array could look something like this:
as you can see this object contains other objects inside of them.
This creates a problem because say i want the name of the object feedback_skill i would have to do the following:
data.forEach(function (x) {
x['feedback_skill']['name']
});
Which cannot be hold into one variable.
Now what i could do is pass the following array: serieKey = ['feedback','name'] suggesting that the first element in the array is the first key and the next element is the variable i want to hit.
However these datasets can have an unlimited number of layers so my question to you guys is:
Is there a smart way of doing this?
I'm not aware of a native JavaScript way of doing this, but various JavaScript frameworks allow you to access deep-properties from objects like this. For example Dojo has lang.getObject and I can see that there is a JQuery plugin that does something similar, lodash as well. If you're not using these frameworks, then you could always create your own util function to perform something similar.
These types of utility function allow you to pass the target as a "dot-notation" property, so you could call:
lang.getObject("feedback_skill.name", false, x)
Using Dojo for example, but they're all much of a muchness.
I don't see any problem with your approach, unlimited number of layers can be handled in the following manner :
data.forEach(function(x){
for(i in seriesKey)
x = x[seriesKey[i]]; // x will contain whatever you wanted to retrieve when the loop ends
doSomething(x);
}
seriesKey can be an array like the one in your example, with as many elements as you need to traverse to the depth you want.

Function param array, how to affect reference = [] or reference.concat(array2)? [duplicate]

This question already has an answer here:
Mutate JavaScript Array Inside Function
(1 answer)
Closed 8 years ago.
So it could just be I'm crazy tired but I can't seem to figure this out.
I've been picking up javascript which I'm finding horrible coming from actionscript 3 where everything was typed. I had a function that referenced two array variables directly, I later needed to use it again for a different data set so I've altered it to take parameters and now it's breaking.
I have one array full of elements, the 2nd is empty. When I call the function, a random element is removed from the first array and pushed into the 2nd array, that element is also returned by the function. If the 1st array is empty I have concat the 2nd array to fill it back up. The goal was to randomly iterate through the elements and not have the selected elements show up again until I had finished a full cycle.
Prior to concat I was using slice(which should work just as well?), the problem I believe is that I know have a parameter that is redefined when I do 'array = array2.slice()', concat doesn't seem to work around that. I don't know if returning the single sliced element from the first array is bad if I'm expecting a string, I think slice is returning an array with the single element, easy fix there though by adding [0] to the return statement.
Heres the code:
//Gets a random element from array, that element is moved from the 'src' array to the 'bin' array,
//this allows random selection without choosing the same element until all of 'src' array elements have been picked
function getRandomElement(array_src,array_bin){
//Randomly selects a tweet from the que, then stores it in another array so each tweet shows once before recycling
if(array_src.length==0 && array_bin.length>0) {array_src.concat(array_bin);} //Recycles array elements when the src array is empty
var randomElement = array_src.splice(Math.floor(Math.random()*array_src.length),1); //Grab a random array element
array_bin.push(randomElement);//array elements stored here to be recycled
return randomElement;
}
I think I could maybe use an object with two properties pointing to the arrays and pass those in, though it'd be nicer if there is a better way. I could also use push on array_src looping through the array_bin to work around that issue if there isn't any other way.
I wouldn't say this is a duplicate Felix. The answer you provided is pretty much the same, but the question itself is phrased differently, I wasn't aware of the term mutate, finding the question/answer wouldn't be easy, none of the suggested links SO provided were relevant. Worth keeping up for making the answer more discoverable to those unaware of the mutate term.
I have a hard time understanding the problem, but I think you are wondering why array_src.concat(array_bin) doesn't seem to do anything?
That's because .concat returns a new array. If you want to mutate the existing array_src array, you can use .push:
array_src.push.apply(array_src, array_bin);
FWIW, this has nothing to do with strong typing. JavaScript (and I guess ActionScript as well), is pass-by-value. That implies that assigning a new value to array_src doesn't change the value of the variable that was passed to getRandomElement.
But since arrays are mutable in JavaScript (and ActionScript I assume), you can mutate the array itself.

Using a for loop to populate an array with objects

I have a function that takes an array, consisting of 3 sets of strings. For each set of strings, the function should spit out 2 resulting integers/numbers.
Link to the jsfiddle of work in progress
So if the input is
["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]
I'm trying to get the function, by using a for-loop, to spit out 2 minute counts for each element of the array (a total of 6 minute counts, 2 per string).
I'm thinking I need the results stored in an object? Or maybe an array, consisting of objects? I'm a little bit confused here.
I'm confused as to how to organize it so that whatever is returned from the function, I can easily access it.
So maybe an array of 3 objects is returned is the best way to do it, with each object consisting of:
1st identifier key: an identifier of some sort (perhaps using the [i] from the for loop),
2nd key/property time1min: with the value being time1min (which is the 1st minute count),
3rd property time2min: with the value being time2min for that string.
As you can see from my jsfiddle above, I'm lost as to how to output to an object, or to an array of objects.
results is an array; so results[0].time1min
Try using console.log(results); instead. It plays nicer than alerts.

Jquery returns a list using id selector

I'm having trouble with jquery and selectors using the following code:
<div id="test"></div>
console.log($('#test'));
This always returns a list like [<div id=ā€‹"test">ā€‹</div>ā€‹] instead of the single element.
This results on always having to write $('#test')[0] for every operations instead of only $('#test'). Any idea on why?
Regards
Jquery will not return the HtmlElement, it returns a jQuery object.
A jQuery object contains a collection
of Document Object Model (DOM)
elements that have been created from
an HTML string or selected from a
document. Since jQuery methods often
use CSS selectors to match elements
from a document, the set of elements
in a jQuery object is often called a
set of "matched elements" or "selected
elements"
The jQuery object itself behaves much
like an array; it has a length
property and the elements in the
object can be accessed by their
numeric indices [0] to [length-1].
Note that a jQuery object is not
actually a Javascript Array object, so
it does not have all the methods of a
true Array object such as join().
http://api.jquery.com/Types/#jQuery
This is an example of the Composite Design Pattern
The Composite Pattern describes a group of objects that can be treated in the same way a single instance of an object can. Implementing this pattern allows you to treat both individual objects and compositions in a uniform manner. In jQuery, when we're accessing or performing actions on a single DOM element or a group of DOM elements, we can treat both in a uniform manner. http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery
jQuery encapsulates any objects found for a number of reasons. For one, it ensures that no matter what, null will never be returned for example. Rather, the elements found are inserted into a list. The fact that even though you're searching for a single element, the mechanism always remains the same and therefore the results will be placed into an array of one element rather than the element itself.
In jQuery it is better to think of selectors as matching multiple items, and your solution would be best if you use the each syntax to iterate through the matches items...
$('#test').each(function() {
console.log($(this));
});
As ID is not unique, jQuery looks for every element with such ID. So it's always returns a list, because threre is no guarantee that the element is exactly one

Categories