problem with prototypejs event listeners and firing events
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.
You listen the #test div's ag:test event but fire the event on the class so it is very normal that nothing happens. You should listen to the events of the class you are creating but then you cannot catch the instantination event since you cannot attach event handlers before the class is instantinated. So you have to find another way.
Got it! It was a problem with deferred loading. In the original question I had all of the javascript defined in the header. It was failing because when I use $('test'), the element doesn't exist yet. The correct code would be:
<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');
}
});
</script>
</head>
<body>
<div id="test">
</div>
<script type="text/javascript">
var myclass = new MyClass({div_id:'test'});
$('test').observe('ag:test', function(evt){
$('test').insert('<p>Test</p>');
});
myclass.test();
</script>
</body>
精彩评论