From: Xu, Qian on
Hi All,

I wrote some code but it doesn't work.

------------------------------------------
<html>
<head>
<script src="my_broken_script.js"></script>
</head>
<body>
Hello World
</body>
</html>
------------------------------------------
// my_broken_script.js
var MyClass = {
init : function() {
var injectCode = '<button onclick="MyClass.btnClickHandler"
id="btn1">Button 1</button>';
var bd = document.body;
bd.innerHTML = injectCode + bd.innerHTML;
},
btnClickHander : function() {
alert('Done');
}
}

MyClass.init(); // <-- Error
------------------------------------------

Browser says "MyClass" has no property. But if I replace
onclick="MyClass.btnClickHandler" with onclick="alert(0)", it works. How
to bind an event to MyClass.btnClickHander ?

BTW: If I bind this event using Prototype, it works.




--
Xu, Qian (stanleyxu)
From: Tom de Neef on
"Xu, Qian" wrote:
> ------------------------------------------
> <html>
> <head>
> <script src="my_broken_script.js"></script>
> </head>
> <body>
> Hello World
> </body>
> </html>
> ------------------------------------------
> // my_broken_script.js
> var MyClass = {
> init : function() {
> var injectCode = '<button onclick="MyClass.btnClickHandler"
> id="btn1">Button 1</button>';
> var bd = document.body;
> bd.innerHTML = injectCode + bd.innerHTML;
> },
> btnClickHander : function() {
> alert('Done');
> }
> }
>
> MyClass.init(); // <-- Error
> ------------------------------------------
>
> Browser says "MyClass" has no property. But if I replace
> onclick="MyClass.btnClickHandler" with onclick="alert(0)", it works. How
> to bind an event to MyClass.btnClickHander ?
>

A few changes help:
<html>
<head>
<script src="my_broken_script.js"></script>
</head>
<body>
Hello World
</body onload = MyClass.init()>
----------^ so that the DOM is complete
</html>

// my_broken_script.js
var MyClass = {
init : function() {
var injectCode = '<button onclick="MyClass.btnClickHandler()"
------------------------------------------------------------------^ brackets
id="btn1">Button 1</button>';
var bd = document.body;
bd.innerHTML = injectCode + bd.innerHTML;
},
btnClickHandler : function() {
----------------^ spelling "l" missing
alert('Done');
}
}

// MyClass.init();
^ now in onload

Tom



From: Xu, Qian on
Tom de Neef wrote:
>
> // MyClass.init();
> ^ now in onload
>
> Tom
>
>
>

Thanks, but this does not help. I am more interested in Why?


--
Best regards
Xu, Qian (stanleyxu)
http://stanleyxu2005.blogspot.com/
From: Xu, Qian on
Tom de Neef wrote:
>
> // MyClass.init();
> ^ now in onload
>
> Tom
>
>
>

Thanks Tom, but this does not help. I am more interested in Why?

One thing I do not get, when button is clicked successfully,
MyClass.btnClickHandler would be called. I called "alert(this.tagName)",
it is "BUTTON" not "MyClass". The "this" pointer should not be MyClass?

--
Best regards
Xu, Qian (stanleyxu)
http://stanleyxu2005.blogspot.com/