functions which acts as a property or method

Topics: General, Language Specification
May 20, 2014 at 8:58 PM
Hi.
I wasn't able to find a better Subject, hoping the one I choose is not that bad... I've already searched quite long for this issue in Bing, Google, StackOverflow and CodePlex but I can't find a solution, maybe because I don't know exactly which are best keywords to look for...
Let me explain with a sample (http://medialize.github.io/jQuery-contextMenu/demo/input.html)
We have a
$.contextMenu(selector)
which is the "standard" call to attach the plugin to an html element; to perform custom actions, we need to call something like this
[...]
hide: function(opt) {
                // this is the trigger element
                var $this = this;
                // export states to data store
                __$.contextMenu.getInputValues(opt, $this.data()); //PROBLEM HERE!!!
__[...]
The problem is jquery.contextMenu.d.ts doens't contain any definition for getInputValues method and VS refuses to compile the script; I've tried to solve the problem (if any) in the d.ts file and eventually post the fix, but nothing I tried seems to work.
$.contextMenu acts like a methos in the first code and like a property of $ in the second fragment, with its own methods (getInputValues in this sample).
Is there any solution for these situations?
Thanks,
Lorenzo
Developer
May 20, 2014 at 9:51 PM
You can use a function and a module with the same name to achieve this. The declarations will merge and the identifier can be used in either context. So:
module $ {
    export function contextMenu() {
        return 1;
    }

    export module contextMenu {
        export function getInputValues() { return ""; }
    }
}

var r: number = $.contextMenu();
var r2: string = $.contextMenu.getInputValues();
May 20, 2014 at 10:08 PM
You could try this in the d.ts file:
interface JQueryStatic {
    contextMenu: {
        (options?: JQueryContextMenuOptions): JQuery;
        getInputValues: (opt: JQueryContextMenuOptions, data: {}) => void;
    }
}
Though I'm not sure what the types should be (I never used it before ;) ).
Marked as answer by LoreX75 on 5/20/2014 at 3:57 PM
May 21, 2014 at 12:04 AM
Finally it works, many thanks both :)
The first solution (from Danquirk) has a conflict with JQuery itself, as compiler warns that module$ has already been declared...