I have a gallery that I am trying to integrate in my site. I am replacing a and then I want to call the galleries function "function loadGal($)" so the gallery will be rebuilt. But I don't know what kind of parameter to send to it.
Before I changed it, it was called inside "jQuery(document).ready(function($) {"
I just tried to do something like this:
jQuery(document).ready(function($) {
loadGal($);
});
it works fine but I don't know what is the dollar...
The $ is just the name of the parameter. It is nothing special. $ is a valid character of variable names in JavaScript.
However it is often used by libraries such as jQuery or Prototype as it is probably the most characteristic one-letter variable (j or p don't stand out that much) (meaning it is easy to spot and easy to use as you only have to type one character).
The value passed to the ready handler, is the jQuery object (emphasis is mine):
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code
but you can name the parameter however you want. You could also write:
jQuery(document).ready(function(foobar) {
loadGal(foobar);
});
Update: And now that I understood the real question ;)
$ is the jQuery object, so you can write:
loadGal(jQuery);
But note that loadGal might not work if it has to work on the DOM elements and you call it outside the ready handler.
Related
I see sometimes js snippets that are using the $ in front of the argument ($argName).
function someName(arg) {
// some code
// using arg
}
function someName($arg) {
// some code
// using $arg
}
In this js example it works either way with or without the $ in front of the arguments. Can anyone explaine if it has any use?
The $ character is legal in JS identifiers, and is often used simply as a code convention to indicate that the passed parameter is already a jQuery object (as opposed to a native DOM element).
This serves as a reminder that it's not necessary to re-invoke the jQuery $(param) wrapper function on that parameter.
It's also used quite a lot in Angular JS code.
It's sometimes used to reference an object from another library , like JQuery or AngularJS , what you're talking about here looks like AngularJs's dependency injection to me
UPDATE
See this answer it might be useful
I have a page where users can choose to book a ticket for a concert. First, they click on a artist which launches them into the booking process (and passes "artist" to the starting function).
The program then loads the venues for the artists. When the user changes the venue (and the value isn't blank) it tried to load the dates available in another select drop down menu by calling another function.
The original code was like:
<select onchange="loadDates(artist)">...</select>
However for some reason this wasn't passing the parameter from the starting function to the next function.
So I changed it too:
<select onchange="loadDates.call(this, artist)">..</select>
However the next function still gives me the error "artist is not defined" when I try to run it. Can anyone see what I'm doing wrong here as I read online that this works perfectly. I can give more information if need be. Thanks
Code in onXyz attributes is run at global scope, so both of your examples require that there be a global variable called artist. If there isn't one, then you'll get a ReferenceError because you're trying to take the value of a symbol that isn't defined.
If you meant to pass a string, put quotes around it. If you meant to pass something else, you'll need to say what that was. But the fundamental issue is that artist is not a defined symbol at global scope, which is where you're trying to use it.
If you have artist defined in some non-global location (good! globals are a bad thing), then you'll want to hook up your event handler via modern techniques rather than using the onXyz attributes.
The simplest way if you're not using a DOM library (like jQuery or similar) is to assign to the onXyz property of the select box element:
(function() { // Something to keep the stuff inside from being globals
var artist = "Joe Cocker";
var selectBox = document.querySelector("selector for the select box");
selectBox.onchange = function() {
loadDates(artist); // `artist` is in scope now
};
})();
In general, though, I avoid the onXyz properties because they only allow a single handler per event per element, preferring the DOM method addEventListener (and its Microsoft-specific predecessor, attachEvent). I didn't use them above for simplicity. If you don't use a DOM library, you might want this hookEvent function given in another answer which uses addEventListener if it's there, or attachEvent if it isn't, and supplies some missing bits for the attachEvent browsers.
I am using .on() to add listeners a few items in my DOM - one input range field, and a number of blocks with the class .colorBlock. These event listeners only need to be active intermittently, and I would like to turn them .off() when they are not in use. Doing this means using a named function instead of an anonymous one.
So fair enough, except that I need to pass data into the callback functions. I know I can use the second (third?) argument field to pass in an object to the event, which is readable in the callback, but doing so seems to be scoping this to the event, instead of to the DOM node that .on() was listened on. See below for example:
$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);
$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);
In my callback functions, I added an alert for e.data.color and e.data.size, and both call out undefined.
To make matters worse, this is a phone gap app, so I am limited in my options to trace what is getting passed around, so some of what I am assuming could be wrong about what is going on.
Any suggestions?
Thanks.
Let's break down this line:
$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);
It's exactly the same (other than the variables) as this:
var sizeValue = $(this).val();
$('#brushSize').on('touchend', { size: sizeValue }, utils.setBrushSize);
E.g., you're calling $(this).val(), and then passing the result of calling it in as part of your data object. So unless this is already what you want to get the value from at that point, it's not going to work.
If you want to get some information from the element when the event happens, just put that code in your event handler. For example, looking at this line:
$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);
It looks to me like you're trying to get the color from the .colorBlock element that was touched. If so:
$('.colorBlock').on('touchstart', function() {
utils.setColor($(this).data('color'));
});
Or if you're going to reuse it:
utils.setColorFromEventElement = function() {
utils.setColor($(this).data('color'));
};
and
$('.colorBlock').on('touchstart', utils.setColorFromEventElement);
Side note:
There's also a possible second problem with that line. You're using utils.setBrushSize as the event handler. Note that within the call to setBrushSize, this will refer to the DOM element on which you hooked the event, not utils. Now, given the name utils, maybe that doesn't matter, but I thought I'd mention it.
More: Mythical methods, You must remember this
The value you're sending in the arguments object is always going to be the number it was when you called the .on() statement. That function's not going to be dynamically re-called every time the event fires.
Personally I think it's really ugly to have the util class go looking for some DOM element and get its value, when as you alluded, what you really want to do is have your util function run in the same scope as the .on() statement.
Your first instinct was probably correct. You don't want an anonymous function, because you want to be able to call off(). Ideally you want a named function that runs in the same scope as the thing that calls the on() statement. So what you want to do is bind the util function to your current scope:
$('#brushSize').on('touchend', utils.setBrushSize.bind(this));
Then in utils.setBrushSize, $(this) is whatever function you called .on() from.
edit Just a warning on this though: when you call off(), you want to call it like this:
$('#brushSize').off('touchend', utils.setBrushSize);
Not on a new scope-bound version of setBrushSize. JQuery should recognize it as equal to the original function you bound and turn it off.
re-edit I'm realizing now that your val() is in $('#brushSize') as that's the "this" you're trying to call... not the function holding the on statement. In that case you can do it this way:
$('#brushSize').on('touchend', utils.setBrushSize.bind($(this)));
So the solution for this particular problem ended up requiring that I strip this bit of code out of Phone Gap and rebuild it in a browser. I was then able to console.log the event that was being sent to the callbacks, and examine them to understand the event object better.
The solutions was to use event.target. This allowed to get the event.target.dataset.color for the .colorBlock listener, and event.target.value from the brushSize range listener.
So for future me, I would be good to have a solid working version of my app in the browser with the phone gap stuff stripped out, to do better testing for problems like this.
I am trying to understand how to "chain" JavaScript events together like jQuery does. I found a question here on S.O. that was similar to my goal, but I do not understand the code in the answer.
Code Source
(function( window, undefined ) {
...etc...
}(window)
What does that mean? What is it doing? It reminds me of Jquery's $(document).ready(){} function, but I don't know why this person wrapped his code in this anonymous function that passes window and undefined.
My ultimate goal is to figure out how to execute methods on an object by chaining methods together like jQuery. I know that jQuery already does this but I am looking into this primarily for growth as a developer.
It defines a function (using a function operator as opposed to a function statement). The parenthesis around it ensure that it is treated as the operator rather than the statement.
It then executes it immediately, passing window as an argument.
Essentially, this is the same as:
var myFunction = function( window, undefined ) {
...etc...
};
myFunction(window);
… but without the interstitial variable.
This has nothing to do with jQuery style function chaining, where each method effectively ends with return this (so calling a method on the return value of another method is the same as calling it on the original object).
When a function is called with fewer arguments than its signature contains, the trailing arguments are assigned the value undefined.
So the above is a roundabout way of getting hold of the undefined value even if some lunatic has redefined it by saying var undefined= 'hello';. (This is illegal anyway in ECMAScript Fifth Edition's ‘strict mode’, but JavaScript coders do some weird things sometimes.)
There isn't really a good reason for passing in window like this though... the traditional way to get window if you can't rely on window is to call a function directly and use this.
Either way, this is simply defensive coding against pathological author JavaScript. It's not something you should worry about whilst writing your own code (in any case there's no way you can stop every way someone might mess up their JS environment), and it's nothing to do with chaining.
Pouring over the release notes regarding jQuery 1.4, I came acrosss $.noop() which is:
Description: An empty function. (added in 1.4)
You can use this empty function when you wish to pass around a function that will do nothing.
Perhaps I'm missing something profound here, but what exactly is a practical use of passing around an empty function?
Code examples appreciated.
This function was proposed due to performance issues on embedded systems when using $.ajax, reported on the jQuery-Dev mailing list. You can see the thread.
Basically, they preferred to introduce and use this single empty function, rather than declaring empty anonymous functions all around.
Now this function is internally used in the ajax, event and offset modules.
You can give a look to the commit when it was introduced also.
If you have a function that accepts a function as a parameter, and you don't have any code to give it, you can pass $.noop.
I can't think of any such cases in jQuery where the parameter isn't optional in the first place, though.
Unlike writing function(){}, passing $.noop will not create a new function instance, saving a bit of memory. However, if whatever you're passing it to modifies the function object (eg, funcParam.id = 2), passing $.noop will mess things up.
Real World Example (well almost):
jQuery.fn.myAwesomeAjax = function(url, complete) {
return jQuery.ajax(url || this.url)
.complete(complete || jQuery.noop);
};
Use it instead of function (){}
Probably if some bad API requires a function as a parameter, and you don't want to do anything in it, this would be a framework-supported way of making that obvious.
I use a couple of plugins which require callbacks, but for some parts I don't actually want to use a certain callback. So, I put in function() {}.
noop is defined in the jQuery source as
noop: function() {}
so it will fit anywhere you'd use a blank function, such as the above example.
The only logical reason is if you're calling a function that does something AND calls another function, and you want the higher-level function to do its thing without calling a parameter function.
Most of the jQuery functions optionally take a parameter function, so you don't have to pass one in. Maybe there's one or two where that's not the case -- or maybe it's to assist developers with their custom code that behaves like this.
If a function requires you pass a function as an argument maybe? It's shorter to say do_something($.noop) than do_something(function(){}).
Although not by much...
...6 characters...
...yeah, that feature looks quite useless actually.
It can be useful if you have a function that supplies functions to other functions.
Example: You have a List of data. Each item has a Button that does something. The "something" can be different for every item. You have a "FunctionFactory" that takes in the item and returns a function. If you don't want the button to do something for whatever reason, then the cleanest way could be to return an empty function, as that way you know that your Factory ALWAYS returns a function.
I don't have a concrete example for jQuery, but I guess this could come in handy when used in an .each or .map block.
It's purely a convenience/replacement for function(){} in the context of where callbacks are required - I don't think I'll be using it anytime soon.
I bet the jQuery team had quite a laugh when they dropped it in though, also serves a comedic purpose.