• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

In prototype.js, Event.observe method is very useful.
But it is a bit inconvenient if you want to handle events only once such as an initialization.
I have often encountered such situation, so I wrote a small utility function being as follows.

js>>
Event.observeOnce = function(element, event, observer){
var handler = function(){
Event.stopObserving(element, event, handler);
return observer.apply(null, $A(arguments));
};
Event.observe(element, event, handler);
};
<<--

The usage is same to Event.observe.

js>>
Event.observeOnce(document, 'dom:loaded', function(){
/* some code goes here */
});
<<--

It may be useful if you copy this into public/javascripts/application.js for Rails applications.

posted by takiuchi takiuchi on Thu 28 Feb 2008 at 17:23 with 0 comments