I am learning the prototype framework and javascript in general and am tring to refactor a bit of existing code to create some html from data inside of a class using an event listener. I am having problems getting the events to fire and getting the corresponding listener code working. Here is a small example, that I can't get working:
<html>
<head>
<title>Event Test</title>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
MyClass = Class.create({
initialize: function(args) {
this.div_id = $(args['div_id']);
},
test: function() {
this.div_id.fire('ag:test');
}
});
var myclass = new MyClass({div_id:'test'});
$('test').observe(myclass, 'ag:test', function(evt){
$('test').insert('<p>Test</p>');
});
myclass.test();
</script>
</head>
<body>
<div id="test">
</div>
</body>
My intention is that I just want to add a bit of html to the div when the class is instantiated, or when some other method is called on the class. Right now this code doesn't do anything. Using firebug, it seems that my class is never being instantiated here. I've been looking at examples and the prototype docs, but can't figure out what I'm doing wrong.
Thanks!
EDIT: Changed to not fire event in the class constructor.