Question

Is there a way to find out if a function in a namespace exists? I'm trying to get the attribute value of an HTML element and then checking if the string value has a corresponding JavaScript function.

<a id="myLink" href="http://stackoverflow.com/" data-success-callback="$.Namespace.SomeFunction" />

var successCallback = $('#myLink').data('success-callback');

I know I can use typeof window[callback] === 'function' to check for functions declared globally but this doesn't seem to work with functions in a namespace; it's undefined.

Is there a way to handle this?

Thank you :)

Was it helpful?

Solution 2

I used this instead:

function getProperty(objName) {
    var parts = objName.split('.');
    for (var i = 0, length = parts.length, obj = window; i < length; ++i) {
        obj = obj[parts[i]];
    }
    return obj;
}

Got it here: Access namespaced javascript object by string name without using eval

OTHER TIPS

Assuming callback is your successCallback object doing window[callback] === 'function' will only check that there is an object called '$.Namespace.SomeFunction' at the root of the window object. But what you want to achieve is to check if there is an object called SomeFunction in the object Namespace itself contained within the $ object.

To do so you can either use what @rps wrote aka typeof typeof myNamespace.myFunc if you already know the namespace and the function or use the below function that will traverse an object and look for a given path, in your case $.Namespace.SomeFunction :

var get = function (model, path, def) {
    path = path || '';
    model = model || {};
    def = typeof def === 'undefined' ? '' : def;
    var parts = path.split('.');
    if (parts.length > 1 && typeof model[parts[0]] === 'object') {
      return get(model[parts[0]], parts.splice(1).join('.'), def);
    } else {
      return model[parts[0]] || def;
    }
  } 

and now do something like

typeof get(window, '$.Namespace.SomeFunction', 'undefined') === 'function'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top