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.
Related
Inside a directive I am trying to get a list of all event names that can potentially be captured by the given scope.
When observing the scope object, I can see that there is a $$listeners property, which contains a single function, and a $$listenersCount property, which does in fact seem to contain a list of events which I have defined that are relevant to the given scope.
I am listening to most of these events on child scopes of the one that is displayed, so I'm assuming this is a list off all events "passing through" the given scope, not events which the specific scope is listening to. I'm unsure what the numbers mean, though.
I can't find any documentation on these properties so I am assuming they are an internal thing that shouldn't be used for this specific purpose.
Are there any other ways of retrieving a list such as this or do you think it's safe to use despite the lack of documentation?
Let's first consider using $$listeners. Like #Blackhole quoted in his comment:
To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.
-Angular Api
So $$listeners is private to angular. It has no documentation and can introduce a breaking change at any moment without notice. Also it's not exactly what you want. By looking at the code of $scope.$on we can see that, like you guessed, $$listenerCount bubbles up the scope to its $parent, all the way to root. The numbers are a count of how many listeners are listening to that one event. You might be able to get away with using $$listeners if you were developing some internal tool to debug events, but using in a production site would not be the wisest thing.
So what would be a documented way to achieve this? Angular provides a decorator method on its provider. While the documentation on this is little, it is quite a powerful tool. It essentially allows interception of any part of angular, and act as a man in the middle (see more info on the Decorator pattern and Monkey patching on Wikipedia). Using these tools we can create a configuration that will capture each instance of $on being called:
.config(function ($provide) {
function wrap(oldFn, wrapFn) {
return function () {
return wrapFn.bind(this, oldFn)
.apply(this, arguments);
}
}
$provide.decorator('$rootScope', function ($delegate) {
var proto = Object.getPrototypeOf($delegate);
proto.$on = wrap(proto.$on, function ($on, name, listener) {
var deregister = $on.call(this, name, listener);
console.log(this, name, listener, deregister);
return deregister;
});
return $delegate;
});
});
Here I have logged each time $on is called. The $scope is the this variable, name and listener are the arguments passed to $on, and deregister is the return value. Note that his requires ES5's Object.getPrototypeOf, and will add overhead each time $on is called.
From here, getting the potential event listeners is easy. Instead of console.log, you could place them into a map, or hook into specific ones. You could also wrap the listener or delistener and do additional work every time they get called. Here is an example plunker of that.
This is better than using $$listeners, because $$listeners can change in any way, at any time. $on on the other hand, is a published API. It will be far more stable, and it will not change without a "Breaking Change" notification in angular's changelog and is the safer choice, even though it uses more anomalous tools.
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.
Sometimes I see in Javascript functions that, if the conversion of a variable to jQuery is used repeatedly, then it can be assigned to a local variable first:
$variable = $(variable);
Is this necessary, and how much is the cost of conversion?
No matter what, storing the object is faster than having to re-instantiate a jQuery object every time you want to use jQuery methods on it...even if it's miniscule for caching $(this) or $(anObject).
A term used to describe this method of "store now, use later" is "caching". The reason it's often called "caching" is because caching refers to storing a reference to something once and using that, without going back out to grab the same thing again, later (very non-technical, non-100% accurate description).
The major point is dealing with selectors. jQuery has to query the DOM every time, which is the expensive part. Generating the object and storing references isn't that expensive compared to DOM manipulation (and jQuery processing your selection in the first place).
If you're simply creating a jQuery object out of an object reference, it's not nearly as devastating, as the processing that takes place is the creation of the jQuery object...so it's really limited to whatever jQuery does for that. It's still good practice and still prevents some unnecessary processing. For example, this:
var element = document.getElementById("div_id");
$(element).someMethod();
// Later:
$(element).someOtherMethod();
is slightly inefficient, since a new jQuery object is created each time. It could easily be condensed to store a reference to a single jQuery object in a variable, and reference that.
The one caveat I can think of is that it isn't a live list of elements (if selecting DOM elements). For example, you may want to cache all elements with the class testing-class, like so:
var myelements = $(".testing-class");
But if another element is added to the DOM with the testing-class class, myelements will not be reflected. It will have the same, previous list. So in that case, the DOM will obviously need to be re-queried and update myelements.
To me, the best practice for caching is within a scope....not the entire page. If you are running a function, and it selects some elements, cache it at the beginning, and use that. But don't cache it globally and use it throughout your page; cache it for an execution cycle.
For example, I would do this:
function someFunc() {
var elements = $(".class-stuff");
// Use `elements` here
// code
// Use `elements` here
someOtherFunc(elements);
}
function someOtherFunc(el) {
// Use `el` here
}
someFunc();
// Some time later:
someFunc();
but I wouldn't do this:
var elements = $(".class-stuff");
function someFunc() {
// Use `elements`
}
function someOtherFunc() {
// Use `elements`
}
someFunc();
someOtherFunc();
// Some time later
someOtherFunc();
It depends on what the variable is. If the original variable is just a single DOM element then it's not particularly expensive - the DOM traversal has already been done so all you're doing is wrapping that element in the jQuery pseudo-array and attaching the prototype.
However if the original variable is a selector, then you absolutely should cache the result to avoid repeated conversions from DOM -> element list.
In any event, it's good practise not to repeat yourself, so caching $(variable) is just good code hygiene.
If the $(variable) is being called anyway this assignment has basically no cost -- this is only storing a reference to the object in memory.
Purists might point out that because the jQuery object is now stored it can't be garbage collected, and this is true. So I guess if you had lots of these it could cause a memory issue, but in itself it has no cost to speak of.
The reason it is done is because there is a cost associated with creating the object, that is the $(variable) part. That if done many times could be expensive. Store a reference to the object means only one needs to be created.
Another important point: The following statement
var $variable = $(variable);
could act different if it is done in a calling context of a closure. That is if there is a function defined in the scope of the var statement that variable will "stick around" for the function to use. This could have the same effects as described above (no gc and pointer memory) with the addition of a longer lifetime. (Because it will stay as long as the function has potential to be called.)
Does anyone know why this would not work in IE7/8?
drop_area = $('div#drop_area');
It works perfectly in IE9, FF2/3, and Chrome. Internet Explorer 7/8 gives the following error:
SCRIPT438: Object doesn't support this property or method
Edit: This is the HTML that goes with my javascript:
http://pastebin.com/nwxx8RzW
IE has a weird behaviour to register some properties in global scope. Elements with an given ID may be accessed simply by using the ID.
So you have a element with the ID "drop_area", it's accessible in IE by using this ID, try:
alert(drop_area.tagName)
..to check it.(should give "DIV")
So what happens: You try to assign something else to this element when using drop_area = $('div#drop_area'); , but this is an invalid operation on an DOMElement.
So use the var-keyword to clarify that you want to create a variable
var drop_area = $('div#drop_area');
or in the case that you have to create a global variable inside a function, assign the variable to the global context:
window['drop_area'] = $('div#drop_area');
The code you've shown on pastebin has numerous global variable issues. In other words, you are coding assuming that variables you are declaring are local in scope, whereas in reality they turn out to be global. Examples include set, box_handle, elements, i, id, drop_area, element, row, image_id, etc. All of your functions are global in scope as well, when they can easily be encapsulated in an other function.
Now I don't know if there's some subtle interactions going on, whether some code has hammering (global) data set by other code, but it certainly seems as if something is getting overwritten and hence methods and properties are disappearing. I would start by going through the code and adding var to local variables. Next I'd be encapsulating most of this code in an anonymous autoexecuting function.
Usually that error shows, that you use jQuery on a website that also uses Prototype. That's why get an error (which is actually throw by Prototype). The other possibility is, that you try to call the code, before the jQuery lib was included into the HTML.
To make sure it's not my first guess, add this code to your JS code:
$.noConflict();
Therefore it is important that Prototype is included into the HTML, before jQuery is included: http://api.jquery.com/jQuery.noConflict/
If you than replace all occurrences of $() with jQuery() and it works, it was the first issue with using jQuery and Prototype at the same time.
Have you got an element with an id of 'drop_area'? ie 6/7/8 auto assigns a global var to the dom element using the element id. Some more code would be helpful.
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.