Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object context of 'this' within a jQuery event

Say I have the following defined in javascript:

com.company.long.namespace = {
    actions: {   
        add: {  
            defaults: {
                url: 'myurl/submit',
            },

            invoke: function () {   
                var submitUrl = this.defaults.url;                          
                com.company.long.namespace.foo.util.server.submit({
                    url: submitUrl,
                    success: function() { }
                });
            },
        }
    }
};

which I then call with within the context of a JQuery click event:

$(myElem).click(function() {
    com.company.long.namespace.actions.add.invoke();
});

Because of the way 'this' works within jQuery event callbacks, this.defaults is undefined when called from this context. Is there anyway to still make use of 'this' within this scope, without having to define the full namespace, or without using jQuery.proxy?

like image 313
cweston Avatar asked May 03 '11 19:05

cweston


1 Answers

You can't call add, it's not a function.

If you call the add.invoke function, this.default is the default object that you have defined in the add object. You don't have to do anything special.

Example: http://jsfiddle.net/p4j4k/

like image 68
Guffa Avatar answered Sep 23 '22 01:09

Guffa