Can anybody explain Code Snippet. ajax cache functionality

how variable is visible in javascript function call back

function getAjaxData(){
    var **$node** = $('#note_container');
    if ($node.data('ajax-cache').length == 0) {
        $.ajax({
            // do stuff. 
            success: function(data){
                // Add dialog content How this node is visible in two scopes?
                **$node**.html(data).data('ajax-cache',data).dialog();
            }
        });
    } else {
        $node.html( $node.data('ajax-cache') ).dialog();
    }
}
getAjaxData();

Instead of making second request values are stored in node .But how node can be visible in the second first order function
It is two nested scopes deep inside of the function.
Is it the reason angular was created and such frameworks?

Please format the code - it’s harder to read without indentation. Just surround it with three backticks prior to and after the code and it will maintain code formatting.

As to how $node is visible … it is a matter of scope. Variables declared in enclosing functions are visible to functions defined inside of those functions. $node at the top of the getAjaxData function - that means all functions defined inside of getAjaxData have access to $node for the life of those functions. This is an example of what is called a closure.

If you had redefined $node inside of success() it would be a new variable and the earlier $node variable would not be visible.

~Micheal

1 Like

Thank you. It is my first question. Didn’t know how formatting work on this forum.
It was formatted when i copy pasted, but in the end it became unreadable.