46
var testObj = this.getView();

How can I check with DoJo (or just native JS) if testObj has callableFunction before I actually try to call callableFunction() and fail if it isn't there? I would prefer a native-DoJo solution as I need this to work on all browsers.

antonpug
  • 13,724
  • 28
  • 88
  • 129

3 Answers3

98

You can call it like this:

testObj.callableFunction && testObj.callableFunction();

or in details:

if (typeof testObj.callableFunction == 'function') {
    testObj.callableFunction();
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 5
    @Ethan In the his case it's safe to use == since typeof operator always returns string type. But if you use === in the project then for consistency sake — yes. – dfsq Nov 30 '15 at 04:43
  • @dfsq Thanks for clarifying. So, if we need to check for non existence, we can comfortably do == "undefined". – Ethan Nov 30 '15 at 10:59
4

dojo has a function that you can use to perform the test.

require(["dojo/_base/lang"], function(lang){

  var testObj = this.getView();
  if(lang.isFunction(testObj.callableFunction)){
    testObj.callableFunction();
  }

});
Craig Swing
  • 8,152
  • 2
  • 30
  • 43
3

You should test that the property exists and is a function:

var returnFromCallable = typeof testObj.callableFunction === 'function' &&
    testObj.callableFunction();
jbabey
  • 45,965
  • 12
  • 71
  • 94