How to solve "cannot call method ... to undefined" in google closure (creating simple toolbar)?

Evgeny picture Evgeny · Feb 21, 2010 · Viewed 29.5k times · Source

below is a complete HTML source for building a simple toolbar with google closure.

Gives an error message in Chrome: Uncaught TypeError: Cannot call method 'addChild' of undefined at the spot marked with // ERROR comment.

Could anyone suggest a tip fixing this? Thanks!!!

edit: that's right, missed new, but another error was that I should have used render() instead of decorate(), because decorate() requires all dom elements in place (and I don't have placeholders for the buttons defined), while render() creates new ones.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 


<script type="text/javascript" src="/m/google-closure/closure/goog/base.js"></script> 
<script type="text/javascript"> 
    goog.require('goog.dom');
    goog.require('goog.ui.Toolbar');
    goog.require('goog.ui.ToolbarButton');
</script> 
<script type="text/javascript"> 
    var load_sketcher = function(){
        var tb = goog.ui.Toolbar();
        tb.addChild(new goog.ui.ToolbarButton('A'), true);// ERROR!!!
        tb.addChild(new goog.ui.ToolbarButton('B'), true);
        tb.decorate(goog.dom.getElement('sk_toolbar'));// should have used render() here
    };
</script> 

</head> 
<body onload='load_sketcher();'> 

<div id="sketcher"> 
    <div id="sk_toolbar"></div> 
    <div id="sk_canvas"></div> 
</div> 

</body> 
</html> 

Answer

Hogan picture Hogan · Feb 21, 2010

There may be other problems, but the error is because you need the new keyword so the line should look like this:

 var tb = new goog.ui.Toolbar();