The situation is somewhat like-
var someVar = some_other_function();
someObj.addEventListener(\"click\", function(){
some_function(someVar);
}, false);
<
You could pass somevar by value(not by reference) via a javascript feature known as closure:
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',function(someVar){
return function(){func(someVar)}
}(someVar));
someVar='changed'
Or you could write a common wrap function such as wrapEventCallback
:
function wrapEventCallback(callback){
var args = Array.prototype.slice.call(arguments, 1);
return function(e){
callback.apply(this, args)
}
}
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'
Here wrapEventCallback(func,var1,var2)
is like:
func.bind(null, var1,var2)
just would like to add. if anyone is adding a function which updates checkboxes to an event listener, you would have to use event.target
instead of this
to update the checkboxes.
Here's yet another way (This one works inside for loops):
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);
var EV = {
ev: '',
fn: '',
elem: '',
add: function () {
this.elem.addEventListener(this.ev, this.fn, false);
}
};
function cons() {
console.log('some what');
}
EV.ev = 'click';
EV.fn = cons;
EV.elem = document.getElementById('body');
EV.add();
//If you want to add one more listener for load event then simply add this two lines of code:
EV.ev = 'load';
EV.add();
Probably not optimal, but simple enough for those not super js savvy. Put the function that calls addEventListener into its own function. That way any function values passed into it maintain their own scope and you can iterate over that function as much as you want.
Example I worked out with file reading as I needed to capture and render a preview of the image and filename. It took me awhile to avoid asynchronous issues when utilizing a multiple file upload type. I would accidentally see the same 'name' on all renders despite uploading different files.
Originally, all the readFile() function was within the readFiles() function. This caused asynchronous scoping issues.
function readFiles(input) {
if (input.files) {
for(i=0;i<input.files.length;i++) {
var filename = input.files[i].name;
if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
readFile(input.files[i],filename);
}
}
}
} //end readFiles
function readFile(file,filename) {
var reader = new FileReader();
reader.addEventListener("load", function() { alert(filename);}, false);
reader.readAsDataURL(file);
} //end readFile
The following code worked fine for me (firefox):
for (var i=0; i<3; i++) {
element = new ... // create your element
element.counter = i;
element.addEventListener('click', function(e){
console.log(this.counter);
... // another code with this element
}, false);
}
Output:
0
1
2