Calling methods in prototype?

1 view
Skip to first unread message

OmenKing

unread,
Jan 29, 2008, 4:02:04 PM1/29/08
to Ruby on Rails: Spinoffs
Hi Prototype User Group!
I'm having a bit of trouble.
I'm trying to call methods: create and destroy but they don't work.
"this.destroy is not a function"
I think I'm missing a step here.

var Ball = {
b_appear: false,

appear: function()
{
if (this.b_appear)
{
this.create();
this.b_appear = false;
}
else
{
this.destroy();
this.b_reorder = true;
}
},

create: function() { alert('create') },
destroy: function() { alert('destroy') }
}

document.observe('dom:loaded', function()
{
$('ball').observe( 'click', Ball.appear);
});

Any ideas?

Justin Perkins

unread,
Jan 29, 2008, 4:15:50 PM1/29/08
to rubyonrail...@googlegroups.com
You need to bind the "this" object to your Ball object for the event
listener. Also, instead of using anonymous functions as page
initializers, I prefer to utilize named methods (so they can be more
easily extended/detached).

var Ball = {
initialize: function(){
this.ball = $('ball');
this.ball.observe('click', this.appear.bindAsEventListener(this));
},
appear: function(event){
if (this.ballAppeared)
this.destroy();
else
this.create();
},
create: function(){
this.ballAppeared = true;
alert("Creating my ball from: " + this.ball);
},
destroy: function(){
this.ballAppeared = false;
alert("Destroying my ball from: " + this.ball);
}
};
document.observe('dom:loaded', Ball.initialize.bindAsEventListener(Ball));

Have a great day.

-justin

OmenKing

unread,
Jan 29, 2008, 4:41:32 PM1/29/08
to Ruby on Rails: Spinoffs
Thanks for the help!
Reply all
Reply to author
Forward
0 new messages