0
for (var key in obj[i]) {
    dataDump[key] = textField.value;
    var callback = function(zeKey){
       return function(e){
          dataDump[zeKey] = e.source.value;
       }; 
    }(key);
    textField.addEventListener('change', callback);
}

When I load the window, this function gets called automatically, which I don't want and instead I want this to be called only when I do a change.

The main point is calling function(zeKey){...}(key). When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function.

1
  • 1
    Which function? The function that sets the callback? By the looks of it, isn't it supposed to be? Aug 3, 2011 at 13:16

2 Answers 2

1

The following

var callback = function(zeKey){
    return function(e){
        dataDump[zeKey] = e.source.value;
    }; 
}(key);
  1. Calls the anonymous function with argument zeKey.
  2. This anonymous function returns another function. This returned function is assigned to the callback.

If 1 what you mean by "the function is getting called" then this is expected behavior.

This entire code should be called only after DOM is ready. Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready()

The function returned by the function will be called only during the callback.

2
  • Can i write two listners for an a field.. i mean.. textField.addEventListener('change', callback, callback2) where callback2 will be called only during change... a normal function Aug 3, 2011 at 13:24
  • @John Cooper You can write multiple listeners for the same event for an element (that is why _add_EventListener). You do so by, well, adding two listeners: element.addEventListener('click', function1); element.addEventListener('click', function2);
    – Nivas
    Aug 3, 2011 at 18:24
0

Add these code once dom is created. If above code is inside a function, attach to window.load or write these code at the end of page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.