0

Recently, I'm coding javascript with little knowledge of it.

And here's my first javascript code which written this morning.

$(window).load(function(){
    SubMenuHandler.init();
});

var SubMenuHandler = {
    init : function() {
        $("#statisticManager, #deviceManager, #policyManager").click(
            function(event) {
                var url = SubMenuHandler.getUrlFromEvent(event); // <-- These two
                SubMenuHandler.redirectPage(url);                // <-- lines
            }
        );
    },
    redirectPage : function(url) {
        $(location).attr("href", url);
    },
    getUrlFromEvent : function(event) {
        var target = event.target;
        var url = $(target).data("url");
        return url;
    }
}

As you can see, SubMenuHandler is called recursively in the class.

But, I don't see how this is done as good. From my experiences with other languages, they usually use the this keyword instead of using the full name of class, except when accessing static variables.

Is there similar or better way to do this job?

Patrick Jeon
  • 1,684
  • 5
  • 24
  • 31

1 Answers1

3
init : function() {
    var me = this; // <----- this is the magic
    $("#statisticManager, #deviceManager, #policyManager").click(
        function(event) {
            var url = me.getUrlFromEvent(event);

            me.redirectPage(url);
        }
    );
},

It is called "closures"

The random link from google: http://www.javascriptkit.com/javatutors/closures.shtml

And perfect answer here on SO: https://stackoverflow.com/a/111200/251311

Community
  • 1
  • 1
zerkms
  • 249,484
  • 69
  • 436
  • 539