Вопрос

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?

Это было полезно?

Решение

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/

Другие советы

To call a function with a context of your choosing you can use .apply(context) (more info about function.apply and function.call):

com.company.long.namespace.actions.add.invoke.apply(com.company.long.namespace.foo.util.context);

Within the invoke function this will refer to the context object.
Check this jsFillde example

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top