Binding Encapsulated Anonymous Functions Without Repetition
Nov 12, 2004
Normally, if you want to bind encapsulated event listeners to an object you have to test for support and then call the same function in different ways, for example:
if(typeof document.addEventListener != 'undefined')
{
document.addEventListener('click', someFunction, false);
}
else if(document.attachEvent != 'undefined')
{
document.attachEvent('onclick', someFunction);
}
But there's code repetition there - okay not very much, because it's just a function call ... but what if you wanted to use an anonymous function ..? Well you can't - the code repetition would be unacceptible.
Except that I've though of a way :) It's really obvious actually .. but I'm posting this in the hope that others will go "wow, that's blindingly useful" as I did when I thought of it :thumbsup:
Here it is - it takes advantage of square-bracket notation to use a string reference to the supported method:
//identify supported method of adding encapsulated event listeners
etype = (typeof document.addEventListener != 'undefined') ? 'addEventListener' : (typeof document.attachEvent != 'undefined') ? 'attachEvent' : 'none'
//set event name prefix
eprefix = (etype == 'attachEvent' ? 'on' : '');
//if encapsulated event listening is not supported, don't continue
if(etype == 'none') { return; }
so anonymous functions are built like this:
element[etype](eprefix + 'event', function()
{
... code ...
}, false);
Even though attachEvent doesn't require a third argument, it's ignored, so this syntax works for all.
View 13 Replies
ADVERTISEMENT
Jun 13, 2010
I'm not having any luck writing this:
Code:
<a onclick="function(e) {clicked(e, 1);}">hit me</a>
and don't have the option of defining the click event outside the <a> tag.
Is it possible to pass in the click event and an additional parameter to the clicked function?
View 4 Replies
View Related
Jul 25, 2011
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
View 5 Replies
View Related
Oct 16, 2010
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?
View 7 Replies
View Related
May 30, 2010
i'm trying to build a navigation tree, but once i complete it, comes the problem; could someone point me in the direction to solve the multi repetition of the effects? if you like you can have a look to the effect and his faults at 500-1.omnigrafica.it
View 1 Replies
View Related
Jul 13, 2010
when you use the mouse listeners there is any chance to say "don't listen any event during the animation" maybe only during the .mouseOut animation?
View 15 Replies
View Related
Jul 13, 2011
In the following code I am trying to pass the return value of the function "getrownum" to the PHP code...but the problem is, when i am trying to pass the return value of the forementioned function, i got no result. "please find my attempts highlighted below in red"code...
View 24 Replies
View Related
Apr 12, 2010
I have an piece of html in a jquery object. When I say $(this).html I get:
<span class="value">4</span><span class="type">teaspoons</span>butter
I want to get only the piece of text from this html segment that is not in the spans. in this example, it is butter.
How do I get that?
View 1 Replies
View Related
Nov 22, 2011
I have this function that works well, but I ask ... is it possible to have a compact sintax to reduce the number of the char inside the text below ??
function change_txarea(val) {
if (val=='I') {
document.FrontPage_Form1.ob1.value = "Description " +[code3].....
View 5 Replies
View Related
Oct 5, 2009
I have a form that uses several text fields to set the footer of the current page. The fields are "Company name", "Street", "Town" and things like that. When a keystroke occurs in one of those fields, I update the footer with the corresponding info, using the "onkeyup" event. All this works fine. My form also has some checkbox to tell if the infos in the footer must be separated with bullet characters. In such case a bullet must be appended to the string retrieved from the current field, but only if the next footer info is not empty or does not start itself with a bullet. Similarly, if the previous footer info is empty and does not end with a bullet, a bullet must be added at the beginning of the current string. So, I have to make the UpdateFooter() function here below more subtle. From the "this" argument passed to that function, I've been unable to find with jQuery the previous and next <li>-encapsulated "siblings". I'm not sure that I really catched how to use "previous()" and "next()" efficiently.
(...)
<fieldset name="footer_infos" class="invisible">
<ul>
<li>
<input name="footer_company" type="text" size="14" maxlength="36"
[Code].....
View 6 Replies
View Related
Jul 7, 2007
There exists anonymous function, and you could also use a variable to contain such function. But why no class?
I mean, you could do:
$func = create_function('$a', 'print $a;');
$func();
or
function test($a)
{
print $a;
}
$func = 'test'
call_user_func($func, xx);
But there is no:
$class = create_class('', '');
or
$class = 'MyClass'
class $class {}
Why?
View 1 Replies
View Related
Oct 11, 2009
Is it possible to iterate through an anonymous array of strings with a for loop?
Here's what I'm trying to do:
for ( i in ['country', 'city', 'state'] ) {
doSomethingWithString(i);
}
What I want is the string, but what I'm getting is the index number of the array, which I can't use because the array isn't named.
View 5 Replies
View Related
Jan 24, 2009
I'm writing a base class for a project and one of the class's prototypes encapsulates cross browser event listening. One point of confusion is that removeEventListener requires that you know the handler. I don't have this info because I'm creating anonymous functions, so how do I do it?Here's the code:
javascript Code:
Original
- javascript Code
[code]....
View 1 Replies
View Related
Feb 3, 2011
I have a problem with understanding jQuery. In my case I have this JS file with following content (see below). This is an anonymous function, isn't it? The problem is this line:
[Code]...
View 1 Replies
View Related
Jan 8, 2011
I have been struggling with a form wizard all day. I'm using jquery stepy (form wizard) along with validation plugin. To cut a long story short, my first step is to get MySQL connection from form controls details. On submit ('next' button) a check is made on an empty hidden control ('hid').
rules: {
hid: {
required: function(){
return checkDBData();
},
messages: {
hid:
{required: 'SQL not available'},
...(etc)...
So, if the function checkDBData passes, false should be returned, so that the form can progress to the next step. If the connection details fail, true is returned so that an error msg is posted.
Here's the checkDBData function:
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();
$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
}
The return values don't find their way back to the rules. However, if I hard code false and true to the function...
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();
$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
return false; //or return true for testing purposes
}
This works. I assume it's due to the asynchronous nature of the ajax call.
View 2 Replies
View Related
Mar 20, 2010
I'm having trouble with something that I can't explain outside of an example. Code:
Code:
$js_info_tabs = json_encode($valid_array);
$script = <<<JAVASCRIPT
<script type="text/javascript">//<![CDATA[
function changeTo(id) {
[Code]....
I have the code this way in order to consolidate it since I would prefer to do that instead of checking the selected ID and manually checking against all possible IDs (which works flawlessly, it just takes up about 5x the lines and is not modular). What I have above also works, but there is one fatal flaw:
It seems like the anonymous function that is the onclick for each unselected element becomes "return changeTo(tab + '_id')", but I don't want it to be that. I want the argument to actually be what tab is instead of the variable.
What ends up happening is that after changeTo() is called for the first time, any element you click will result in the last element being the selected one, as if it's using the final value of tab as its return value.
This doesn't make any sense, though, since tab is local, and deleting it before the function exists doesn't work. Deleting elem at the end of the for loop doesn't work. I honestly don't understand what's going on or why it doesn't set the new onclick value correctly.
Basically I just want changeTo(tab + '_id'); to turn into changeTo('MYID_id'); instead, but it simply doesn't do that and I can't figure out a way how.
View 1 Replies
View Related
Nov 3, 2011
var name = "good";
load_image( name );
function load_image( name )
[code]....
I've tried giving addEventListerner an anonymous function
View 3 Replies
View Related
Dec 4, 2006
I have several functions with code along the lines of:
var xmlDoc = requestXML("ajax.asp?SP=SelectRelatedTags&tag=" +
array[i]);
The requestXML() function includes the code:
var xmlDoc = null;
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseXML;
} else {
alert('There was a problem with the request.' +
http_request.status);
}}};
http_request.open('GET', url, true);
http_request.send(null);
return xmlDoc;
However, the last line (the return) executes before the readyState
reaches 4. How do I return the xmlDoc to the functions only once the
xmlDoc has been assigned? I tried putting the return statement in a
while loop with the condition that the readyState must = 4 - this
worked, but makes the browser popup a message saying the script is
slowing down the system.
View 1 Replies
View Related
Jun 6, 2009
I did search the forums but couldn't seem to find anything on this specifically. I basically need to pass a key event and a 'name' to nameCheck() after 3 seconds. This works fine in Firefox but Internet Explorer gives the error: Member not found. I'm more of a PHP guy than a JS one
<input type="text" onkeyup="nameCheckTimer(this.value, event)" value="" />
function nameCheckTimer(name, evt) {
setTimeout(function(){return nameCheck(name,evt)}, 3000);
}
function nameCheck(name, evt) {
//need name and the key event to be available here. I have code to handle the key codes which works fine
}
View 6 Replies
View Related
Jun 10, 2010
I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener.So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well.
View 3 Replies
View Related
Aug 2, 2010
I would like to know how to pass in a reference of this to anonymous function so I can access parameters from anonymous. Here is my code:
[Code]...
View 2 Replies
View Related
Feb 28, 2010
I am trying to create an anonymous function for onchange event of file field, so that when a file is selected, the covering text field gets that value. I know how to accomplish this by adding onchange="", but I'd prefer not do that. The code that I have almost works, except that the function in the for loop can't call on the "i" variable that the loop uses.
for( i = 0; i < source.length; i++) {
source[i].onchange = function() {
name[i].value = this.value;
}
}
View 3 Replies
View Related
Oct 22, 2010
//<input type="text" id="s_field" value=""/>
var valid = true;
var div = $("#s_field");
$.post("index.php",{id: 6}, function (data){
[Code]..
When posting data, and getting response need to set valid to false - email is not valid.
1. in function it alerts valid is false
2. outside function it says valid is still true!
even i didn't wrote var valid = false;, but valid = false;I need to set Global "valid" variable to false.
View 1 Replies
View Related
Apr 7, 2003
Im working on a php rpg with some others, but I want to be able to use the arrow keys to navigate the character using the up arrow/down arrow/left arrow/right arrow, and you move your character through links
PHP Code:
var left="<? echo $url.$west;?>"; var up="<? echo $url.$north;?>"; var right="<? echo $url.$east;?>"; var down="<? echo $url.$south;?>";
can ANYONE give me a example for doing this, all i want is when you press the up down left or right it, produces the same result as if you pressed a link. to move left or right etc..
View 2 Replies
View Related
Mar 28, 2010
I'm using jquery to make it easy for AJAX calls.
So I create a class: function cMap(mapID){//vars and stuff}
I go and prototype a function: cMap.prototype.loadMap = function(){ //jquery AJAX call }
Now in the jquery $.ajax({...}); call, I use an anonymous function on the "success:" call: success: function(data){ this.member = data; }
My problem is that inside this anonymous function call I'm trying to call a class member of my cMap class to store the data in from the AJAX call, but it's out of scope. So the JS console in FF/Chrome throws errors about bad value/doesn't exist.
How can I access this class member from inside an anonymous function? Or at least what's a good way to go about doing all this?
View 2 Replies
View Related
Jul 23, 2005
I've created an XML-RPC server, and would like to somehow bind the XML
server responses to a table for users to view. Here's the catch, that data
changes frequently (every few seconds), so I'm using setInterval to
periodically get updated XML content from the server.
Currently, the setInterval function requests the entire dataset, then
rewrites the entire table. I'm concerned that it's a waste of bandwidth,
and disrupts the user scrolling through the data whenever it rewrites.
Ideally, I'll have the XML-RPC server generate only data changed since the
last request, then somehow update the table with the changes.
View 3 Replies
View Related