0

I have a UserInterface class with a public method that needs to be able to delegate its work to a private function based on a parameter. The name of the private wrapper needs to be called dynamically:

function UserInterface() {
  // ...

  this.getViewHtml = function(view) {  
    // Given this snippet, view would be passed in as 
    // either "First" or "Second".

    // Wrong syntax, I know, but illustrative of what
    // I'm trying to do, I think
    return 'get' + view + 'ViewHtml'();  
  };

  function getFirstViewHtml() {
    return someHtml;
  };

  function getSecondViewHtml() {
    return someHtml;
  };


  // ...
}

As you might expect, if I don't have the variable requirement, I can call the private function just fine.

How can I get my public function to access the appropriate private method using a variable-based function name? This is outside of any window object, so window['get' + view + 'ViewHtml'] doesn't work.

Any insight would be appreciated.

Rob Wilkerson
  • 40,476
  • 42
  • 137
  • 192

1 Answers1

0

You need to define your private functions as methods of a private object:

function UserInterface() {    
  this.getViewHtml = function(view) {
    return methods['get' + view + 'ViewHtml']();  
  };

  var methods = {
    getFirstViewHtml : function() { return someHtml; },
    getSecondViewHtml : function() { return someHtml; },
  }
}

Alternatively you could use a switch:

this.getViewHtml = function(view) {
  switch(view) {
    case 'first': return getFirstViewHtml();
    case 'second': return getSecondViewHtml();
    default : throw new Error('Something is terribly wrong');
  }  
};
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • Yeah, I was hoping to avoid the switch/case approach. I've never seen the private object approach, but will try it. It seems kind of hacky on the face of it, but maybe that's just because it's new to me. :-) Thanks. – Rob Wilkerson Jan 28 '14 at 13:05
  • 1
    It's about as hacky as the window['get'+stuff] approach. I don't see any problems with it usually associated with hacks, so you're probably good to go. – Tibos Jan 28 '14 at 13:09