0

I'm trying to make a controller for my app. I'm not able to do what I want and I don't understand why :-( I'm not a javascript expert so probably I'm doing something that is not allowed. Error from firebug:

TypeError: window[("Controller." + where)] is not a function

The error is clear, but why is this happening?

jsFiddle: http://jsfiddle.net/TB8yr/1/

var Controller= function(){
    this.currentpage='home';

}

Controller.prototype.route=function(where){

    window["Controller."+where]();
};

Controller.prototype.goHome=function(){
    alert('route gohome');

}

Controller.prototype.goBack=function(){
    alert('route goback');

}

//////
test=new Controller();
test.route('goHome');
2
  • Controller is not in window. Do var Controller = window.Controller = ... Commented Dec 6, 2013 at 16:51
  • possible duplicate of Dynamic object property name Commented Dec 6, 2013 at 16:56

2 Answers 2

4

You should use this instead.

this[ where ]();

jsFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

thank you bro! I did try different combinations but I wasn't clever enough to do it this way! thank you again, it works.
2

You have a few problems:

First, jsFiddle runs all of its code inside an IIFE. Declaring a variable in the javascript section will not append it to the window object of the page.

Second, you can't nest properties via dot notation in bracket notation like that. E.g. ['parent']['child'], not ['parent.child'].

Lastly, you're trying to call an instance method (goHome) on the constructor function, not an instance. You should be using this inside the prototype methods to refer to the instance.

Working example: http://jsfiddle.net/TB8yr/4/

var Controller= function(){
    this.currentpage='home';    
}

Controller.prototype.route=function(where){
    this[where]();
};

Controller.prototype.goHome=function(){
    alert('route gohome');    
}

Controller.prototype.goBack=function(){
    alert('route goback');    
}

test = new Controller();
test.route('goHome');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.