0

I have this page, where we have three menus

<ul class="support-menu nav navbar-nav nav_menu nav nav-pills nav-stacked full-width">
        <li class="nav_menu"><a href="#" id="manage">Manage</a></li>
        <li class="nav_menu"><a href="#" id="asset">Asset</a></li>
        <li class="nav_menu"><a href="#" id="report">Report</a></li>
</ul>

On the document ready, following code is written

 $(function() {
     var actionUrlMap = {
        manage: "/support/manage",
        asset: "/support/asset",
        report: "/support/report"
    };
    var loadUrl = function (url) {
        $("#resultDiv").load(url);
    };
    for (var prop in actionUrlMap) {
        $("body").on("click", "#" + prop, function (e) {
            loadUrl(actionUrlMap[prop]);
        });
    };
});

But no matter which menu I click, I always get the page

Welcome to Report Support Section

It looked to me that the problem is related with closure, so I changed the code to following

for (var prop in actionUrlMap) {
        var localProp = prop;
        var localUrl = actionUrlMap[localProp];
        $("body").on("click", "#" + localProp, function (e) {
            loadUrl(localUrl);
        });
    };

I thought that now since I am capturing the local variable, it should load the correct url, but click on any of the menu options still loads the

Welcome to Report Support Section

I also tried this

for (var prop in actionUrlMap) {
        $("body").on("click", "#" + prop, function (e) {
            var localProp = prop;
            var localUrl = actionUrlMap[localProp];
            loadUrl(localUrl);
        });
    };

Again, thinking that now I have captured the property in local variable, it should load the correct url, but it is still loading the report help section.

What am I missing here? Am I understanding the whole closure concept wrong? Or something else is missing from the code?

Razort4x
  • 3,296
  • 10
  • 50
  • 88
  • As an alternative you can do `loadUrl(actionUrlMap[this.id.replace('#', '')]);` – Satpal Oct 05 '16 at 11:02
  • @Satpal: Yes, I know I can, but that's not the point. I want to know what am I missing with this closure related thing. – Razort4x Oct 05 '16 at 11:03
  • 1
    "*What am I missing here?*" - the closure is the `function`, and it captures the `prop` variable (and `actionUrlMap` and `loadUrl`, but those don't change their value). `localProp` and `localUrl` are just local variables. – Bergi Oct 05 '16 at 11:05
  • Try taking this function `var loadUrl = function (url) { $("#resultDiv").load(url); };` outside the `.ready` block – Ifedi Okonkwo Oct 05 '16 at 11:13

0 Answers0