Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function parameters

I am working on a project which involves the ExtJS library and I came upon this piece of code which did not make sense (but it works). Please help :(.

TreePanel.on('click', showDocumentFromTree);
function showDocumentFromTree(node) {   
    if (TreePanel.getSelectionModel().isSelected(node)) {
        dataStore.baseParams = {
            node : node.id,
            limit : 10
        }
        dataStore.load({
            params : {
                start : 0
            }
        });
    }
};

So the function definition for "showDocumentFromTree" has a parameter called "node" but when the code calls it, it did not pass in anything. Also, the object "node" is not a global (as far as I know).

So I'm confused on how that works? Is this some magic that Javascript has?

Also, when I do a console.debug to print "node" it has stuff in it. (console.debug for FireBug)

Thank you for your time, J

like image 935
Aion Avatar asked Dec 14 '22 04:12

Aion


2 Answers

When the code is doing `TreePanel.on('click', showDocumentFromTree)', it isn't calling showDocumentFromTree, it's passing the function showDocumentFromTree as an argument. It will then be called later, by the onclick event handler that it's being set up for, and it will be passed its node argument then.

like image 130
chaos Avatar answered Dec 27 '22 16:12

chaos


The first line binds the showDocumentFromTree function to the click event. What is passed to TreePanel.on is a reference to the showDocumentFromTree function, not the call itself.

When an event fires, the bound function(s) will be called, with the triggering object as the first parameter. In this case, it will be the DOM node that was clicked.

To illustrate, the first line can be rewritten to:

TreePanel.on('click', function(node) {
   showDocumentFromTree(node);
});

OK, maybe this is not much clearer, but you can see that it actually passes a function as argument to the on method, rather than calling the method itself.

like image 38
waxwing Avatar answered Dec 27 '22 17:12

waxwing