Arg, I'm losing hair. I'm having trouble understanding something extremely basic and important. I have functions who call functions who call functions.. but I'm having trouble doing anything useful with their results. I can't seem to "grab" them. They just get garbage collected. Scope is becoming my enemy.
This is also hard to explain because the code is modular, so stuff is calling stuff is calling stuff.
Everything happens inside a large Object.
[Code]...
Where do I have to go to understand basic Javascript things like getting values back out of a function? It's always the same problem I hit every time I use functions to figure out some value. It's always locked away.
If anyone happens to know of some place where one can practice with these things, that would be nice.Closures for morons? Functions for dummies? Something like that. I've got bookmarks of pages explaining functions and values and closures but I can't seem to take that over to what I want to do with them.
function attributes() { var attr1 = arguments[0] || '_' var attr2 = arguments[1] || '_' return ( function (el1, el2) { var value1 = el1[attr1] + el1[attr2]; var value2 = el2[attr1] + el2[attr2]; if (value1 > value2) return 1; else if (value1 < value2) return -1; else return 0; } ); }
var a = [ { a:'smith', b:'john' }, { a:'jones', b:'bob' }, { a:'smith', b:'jane' } ]; a.sort(attributes('a', 'b')); for (var i =0; i < a.length; i++) { document.write(a[i].a + ', ' + a[i].b + '<br>'); }
My question is, are attr1 and attr2 guaranteed to exist through the lifetime of a.sort(attributes('a', 'b'))?
As I understand it, the anonymous inner function reference I am returning is a property of attributes(). As such, when I return a reference to the anonymous inner function, the outer attributes() function must continue to exist (as must attr1 and att2) until there are no further references to the inner anonymous function.
As a result, there is no danger of attr1 or attr2 "disappearing" during the repeated calling of the anonymous inner function.
Is my explanation basically correct, or am I deluding myself and I'm just lucky that the garbage collector hasn't recovered attr1 or attr2 while the sort is still going on? In other words, is the behaviour I'm seeing consistent and predictable, or should I change my approach?
When writing JS, I try to encapsulate my code somehow. For instance, in the example below, I have a function ('testFunc') that's encapsulated within jQuery's document.ready callback function :
Code: $(function(){ var testFunc = function(x){ x++;[code]...
If I then start using JS's base timer functions like settimeout, I've always been unsure of how to access the 'testFunc' function. As I understand it, even if the timer functions are called inside the same function, as in...
Code: $(function(){ var testFunc = function(x){ x++; return x; }
var timer = setTimeout("testFunc", 100); });
... they will lose the scope of the jQuery callback - instead the timer functions will only be able to access objects in the global scope.
I have a question regarding how to prevent memory leaks in Internet Explorer when using closures. I already knew about the circular reference problem, and until now was able to prevent memory leak problems. But I needed to store DOM elements and can't solve it anymore. So I search the group archive to see if I missed any valuable information. I found some interesting articles, but somehow could not apply it to my problem or I did not understand it fully. In particular the articles that talked about setting variables to NULL seemed as an easy solution, but I think I didn't understand it, because it didn't seem to work.
So, let me explain my problem in more detail. I am working on some very dynamic and complex page. It uses AJAX (XMLHttpRequest) to alter different parts of the page. This already disqualifies the finalize method solution to cleanup memory leak problems. I use several "component classes" to do the work of creating DOM elements in some container element and provide an easy to use interface for manipulation the content. For example I can call component.setBackgroundColor("red") and the component takes care of changing the style on the correct DOM element that is encapsulated in the component. In reality the component uses more complex interface method, but I hope you get the picture of why I do this.
Let me show you some example code:
function MyComponent() { var div; var handler = null;
this.generate = function generate() { div = document.createElement("div"); div.onclick = MyComponent.createClickHandler(this); // normally more elements are created here return div; }
this.setBackgroundColor = function setBackgroundColor(value) { div.style.backgroundColor = value; }
this.getHandler = function getHandler() { return handler; }
this.setHandler = function setHandler(value) { handler = value; }
}
MyComponent.createClickHandler = function createClickHandler(component) { return function(event) { var handler = component.getHandler(); if (handler != null) handler(event); } }
This "component class" can be used like this:
var container = document.getElementById("container"); var component = new MyComponent(); container.appendChild(component.generate()); .... component.setBackgroundColor("red"); component.setHandler(function(event) {alert("Stop touching me!")});
The problem, of course, is that this code will create a memory leak in Internet Explorer. I need the component in the event handler to get the handler dynamically, but the div is stored there too, creating a circular reference.
One of the things I tried doing is making a DOMStorage "class" like this:
function DOMStorage() { var map = new Object();
this.get = function get(id) { return map[id]; }
this.put = function put(id, obj) { map[id] = obj; }
}
var storage = new DOMStorage(); //global
Instead of storing the div element directly in the component, I store it under an id in the DOMStorage and use it to retrieve it later. This actually prevented the memory leak. I don't really understand why, because I still see a circular reference. Maybe Internet Explorer does not count references in the global scope as a circular reference? When I move the global storage to inside the container object I get the memory leak again.
Unfortunately I am unable to use a global DOMStorage, because the "component class" in instantiated many times, and they must all have their seperate DOM elements.
Perhaps I have to generate unique ID's when I put a DOM element into the global storage? It seems so over-the-top for something that works perfectly fine in Firefox.
1) is getRule a local variable or global variable, as it has no var keyword, yet it is an inner function of Validation? So without var, I think global, but being an inner function, I think local. So I'm not sure which.
2) In this line of code: var rule = $.Validation.getRule(types[type]), getRule returns rules, which is just a local variable in Validation. I always see that you return functions, but how does returning a local variable that's just an object literal and not a function be able to return true or false? Now the value of rules is an object literal, and this object returns true or false. So we are basically allowed to use return keyword with local variables that are object literals and not functions?
3) In this line, is foo(age) being called, or is it just being assigned to bar OR is it being called and THEN assigned to bar: var bar = foo(age);
4) Now for the most confusing: age is obviously an object reference as opposed to a literal in the example. Does that make a difference in regards to closures? Note that I read a number of books, including JavaScript Programmer Reference and Object Oriented JavaScript and jQuery cookbook, which compare primitives vs reference types and how primitive types store directly in memory whereas reference tpyes reference memory, so if one reference changes, they all change where primitive remains ingrained. But when assigning a function as a reference like this, how does that affect the object "age" when passed into bar?
Code: function foo(x) { var tmp = 3; return function (y) { alert(x + y + tmp); x.memb = x.memb ? x.memb + 1 : 1; alert(x.memb); }} var age = new Number(2); var bar = foo(age); // bar is now a closure referencing age. bar(10);
According to ECMAScript, the root of the prototype chain is Object.Prototype. Each object has an internal property [[Prototype]] that could be another object or NULL.... However, it also says that every function has the Function prototype object: Function.Prototype, it confused me, because a function is an object, for a function object, what is its function prototype and object prototype..For example:
var x = function (n) {return n+1;};
what is the relationships of x, Object.Prototype and Function.Prototype
I am trying to get to the bottom of javascript object, prototypes etc. I have a fairly good grasp of it, but I get confused the closer I get to the base object.prototype. FIrst of all, I was under the impression that all objects descend directly from Object. But some objects (like Array) seem to inherit properties and methods from the function.prototype. So does this mean that the chain is like this:
object -- function -- array Second, I noticed (on the mozilla javascript reference site that object.prototype inherits properties and methods from function.prototype and vice versa!? How can this be? I must be missing something important about understanding the chain?
I think the last thing people seem to learn about in JavaScript when they're not coming from other programming languages is variable scope. Some even get all the way into AJAX without having learned about scope, and this is a time when it's really needed. Although the scope of JavaScript variables is non-complex by nature, it's something we should all get a full understanding for before we move too far. Section 1: What is "scope"? Section 2: The "var" keyword Section 3: The "this" keyword Section 4: Closures or "Anonymous functions and self-invoking closures
I am confused about the true difference between the two below examples.
first example:
// Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array();
[code]....
Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed.
I have a couple of problems with this example:
1) I thought a closure is a function that is returned - the inner function is not returned above.
2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function.
3) the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment.
Second example:
// A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array();
[code]....
Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray.
This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved?
I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index?
Throughout the world in general, ISO 8601 Week Numbers are used, in which weeks are numbered 01 upwards and Week 01 contains the first Thursday of the Gregorian Calendar Year.
There are, however, odd parts of the world where that standard is not followed.
Ignoring for the moment cases in which week 1 is not more-or-less at the beginning of the calendar year, what other definitions, stated exactly, are used?
I have this particular problem with eval() when using Microsoft Internet Explorer, when trying to define an event handler. This is the code:
function BigObject() { this.items = new Array(); this.values = new Array(); this.addItem = function( item ) { this.items[this.items.length] = item; } this.makeHandlers() { var i, length = this.items.length; for ( i = 0; i < length; i++ ) this.items[i].onclick = function() { alert( this.values[i] ); }; }}
However, this last code (makeHandlers() method) doesn't work since the expression "this.values[i]" automatically belongs to this new anonymous function, and therefore isn't valid (since the new anonymous function(s) don't have the "values" attribute. So I tried the following:
and it worked! ... in Firefox only :( Internet explorer returns "undefined" for eval( "function() { /* whatever */ ); } " ), for the same things Firefox perfectly understands, and if I try to make it a handler, an exception is fired in IE. What do I do? Did I come to the right conclusion with IE or am I making a banal mistake? Do I need to find another way of solving this or is there a fix to this solution?
I had a look at sIFR.js code after parsing it and I have a question about function syntax. For example
var f=function(){ // statements here }();
What is the purpose if the second set of parentheses following the closing brace? Is the intention to execute the function immediately after it has been defined?
Most functions in sIFR.js do not have this syntax, but a few do.
I'm trying to grab all of the elements of a DL, specifically the <a href>'s grouping them by the DD's. I suppose if I can just get them into groups I can get the href's later. The hard part is getting them grouped as explained below. For example...
Is there a way to say, loop through the DL until it finds a DT. Whe it finds one, grab it and all of the DD's that immediately follow it .. until it comes to another DT. Group it with its DD's and continue until no more DT's are found.
Then maybe take these collections and possibly populate an array with the groups?
There is an effect I would like to do but I don't know how it is done. To see something like it go to:[URL].. then mouseover the right side items under "most recently". It seems like there is a dt link which when mouseover occurs the dd data is presented.
I have pairs of terms and short definitions in a table. I want to display a longer definition in a box below the terms table when the term is clicked on. The box needs to disappear if clicked on. [code]...
I am trying to use multiple instances of this little show/hide script for a definition list on the same page. However, the problem is that the definition list must be given an ID, and this can only be used once on a page. [URL]. How would I go about changing this to a class so that I could use it more than once on a page (i.e. multiple definition lists as opposed to one big one)? I changed all of the getElementById to getElementByClass and it didn't seem to work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
[code]....
The practical scenario is I have several functions attached to the jQuery ajaxSucess event. Each function needs to execute once during initial load and after when the JQuery ajaxSuccess event is fired. So I am just looking to see if I can eliminate a a few lines of code and learn something new in the process, that is really all.
I've got a website with font sizes using 'em's. I've made it so that in my 'body' CSS styling, I can change the font size and it changes it right throughout the whole site.
I have hyperlinks to increase and decrease the font size but have no idea how to get the links to change the 'font-size' property in my 'body' definition. As a secondary requirement (but not essential) I also need to remember this value and store in a cookie so the user doesn't need to keep resizing the page on every reload.
I've always wanted to help second-language English speakers access my site better, by offering a 'double-click on a word' definition in other languages. I had a useful script for some years which was rather dated, and ceased to work if there was an iframe on the page for some reason. Anyway, I found a very good solution at [URL]However, this opens the definition in a new tab/window.
Having experimented with it opening in a popup, I found problems in getting the popup to regain focus if someone had not closed it before looking for another definition. And anyway, popups can get blocked. So I found a nice layer/iframe solution at [URL] though their positioning of the layer is poor, at least in FF because it slides too far down below the bottom of the page. Their script is: [URL]I have modified that to work with dictionarist and stripped out their own floating part of the script, so that it works with position fixed for everything except IE6. But for IE6, I need to still change this from position fixed to position absolute, and then use a script to float the box.I have been trying the script I use successfully elsewhere in a vaguely similar context:
which has a call to startFloat(); near the end, which is based on their own floating script nearer the top of [URL] which I have removed. (Doubtless the references to Netscape (RIP) can be removed.)
I am doing a distionary page with javascript and I am trying to get it so that the definitions come up when the word they are for is clicked on.
Here is my javascript Javascript Document var filename = "dictionary.js"; function loaded(which){ alert(which + " loaded"); }/**/ function showInfo(which){ var placeholder = document.getElementById("definition"); var source = whichInfo.getAttribute("href"); placeholder.setAttribute(source); alert("showInfo called"); return false; }function prepareList(){ if (!document.getElementsByTagName || !document.getElementById) return false; var words = document.getElementById("words"); if (!words) return false; var links = words.getElementsByTagName("a"); for(var i = 0; i < links.length; i++) { links[i].onclick = function(){ showInfo(this); return false; }} alert("prepare list done"); }function init(){ prepareList(); }loaded(filename); window.onload = init;
Here is my html <!DOCTYPE html PUBLIC "-W3CDTD XHTML 1.0 StrictEN" "[URL]"> <html xmlns="[URL]"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Dictionary DOM Scripting</title> <link href="../styles/main.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="dictionaryScripts/dictionary.js"> </script> </head><body> <div class="page"> <div class="nav"><ul> <li><a href="../home.html">Home</a></li> <li><a href="../form/form.html">Form</a></li> <li><a href="dictionaryCSS.html">Dictionary with CSS</a></li> <li><a href="dictionaryDOM.html">Dictionary with DOM scripting</a></li> <li><a href="discussionPage.html">Discussion</a></li> </ul></div><div class="header"> <h1>Dictionary with DOM Scripting</h1></div> <div class="mainContent"> <div id="words"><h2>L</h2> <p>Click on the word to get a definition</p> <dt><a href="lecturer.html">LECTURER, n.</a></dt> <dt><a href="learning.html">LEARNING, n</a></dt> <dt><a href="liar.html">LIAR, n.</a></dt> <dt><a href="love.html">LOVE, n.</a></dt></div> <div id="definition">Choose a definition</div> </div></div></body></html>
I am looping through an array of objects and creating an <li> element for each one and appending to a <ul> in the DOM. Works fine.During the looping I am also attached a 'details' object as data for the list element:$(thisListItem).data('details',{<obj>});Later, I am using the selector:$('ul#images_list li')to attach an on click function for each <li> element.In the click handler I am reading the data 'details' object for the <li> element:dataDetails = $.data(lotImage,'details');and, using the jAlerts plugin, I am opening a jPrompt which asks for the user to enter a price.
The jPrompt call includes a callback which receives the entered value as a parameter. The callback uses the value to 'post' the updated value, via $.ajax, to a server side unction.After OK is clicked in the jPrompt popup, in Firebug, I get an error that the dataDetails is undefined and it lists the line number in the click handler where I originally read the data object from the <li> element.I don't really understand why it should care after the click event has fired and the jPrompt callback has been invoked
I have a simple hide and fadeIn. When you rollover a word it will reveal the definition. The problem I am having is if you move the mouse around quickly from one word to the next word sometimes it gets hung up and a definition will not hide. The result gives this hanging defintion and whatever the other definition the mouse is rolledover.
Here is the code I'm using:
There are about 70 words in a box with the definition being reveals on the right hand side. Is there a way of making sure there is always only one definition being shown?
if the dt-element in one of the definition lists has a specific css-property (e.g. length > 100px) then the dd-element with the css-class "subtitle" in the same definition list should be removed.