Home > database >  calling function inside of anonymous function
calling function inside of anonymous function

Time:06-22

This may have been asked before but I've been searching for it for a few days and trying various ways with no luck.

I'm using a jstree component (simplified below). I'm trying to call the FindUrl function using _MyTree.FindUrl('test'); from outside the function but I just get an error indicating it's not a valid function. Is there a way to call this FindUrl function correctly?

var _MyTree = $(function () {
    var tree = $('#myTree');

    $("#onlyActive").change(function () {
        $('#myTree').jstree(true).refresh();
    });
    $('#myTree').jstree({
        "core": {
            "data": {
                "url": "/Admin/AdminSiteMap/GetJSTreeForAdmin",
                "data": function (node) {
                    return {
                        "id": node.id == "#" ? -1 : node.id,
                        'onlyActive': $("#onlyActive").is(':checked')
                    };
                }
            }
        },
        "themes": {
            "theme": "default",
            "dots": false,
            "icons": true,
            "url": "/Scripts/jstree/themes/default/style.min.css"
        },
        //"core": { "html_titles": true },
        //"themes": { "stripes": false },
        "contextmenu": {
            "items": createDefaultMenu,
            "width": "350px",
            "select_node": true
        },
        "plugins": ["state", "dnd", "contextmenu"]
    });


    function FindUrl(str) {
        console.log("searching for ", str);
    }
});

CodePudding user response:

you can add return function like this

var _MyTree = $(function () {

   .....

   function FindUrl(str) {
        console.log("searching for ", str);
    }
    
return {FindUrl : FindUrl};
});

then you can call by

_MyTree().FindUrl("some string here");

CodePudding user response:

You have to return it as an object & in object you can create init and geturl function. like below example

var _MyTree = {
  Init : function (){
    $(function () {
    console.log('Your JS Tree initalization code here');
    })
  },
  FindUrl : function(str){
    console.log('searching for ', str);
  }
};
_MyTree.Init();
_MyTree.FindUrl('abc');
  • Related