如何在Prototype中添加JS事件处理程序?

时间:2010-06-10 12:21:49

标签: javascript javascript-events prototypejs

我想在Prototype中的现有事件处理程序之前添加一个事件监听器/处理程序。这是一个例子:

<form ... onsubmit="alert('foo')" id="f1">
   $('f1').observe("submit", function() {
     alert('do this before foo');
   });
</form>

1 个答案:

答案 0 :(得分:0)

Observer = Class.create({
 initialize: function() {
  this.callbacks = [];
 },
 prependCallback = function(callback) {
  this.callbacks.unshift(callback);
 },
 appendCallback = function(callback) {
  this.callbacks.push(callback);
 },
 runCallbacks = function() {
  this.callbacks.each(
   function(callback) {
    callback();
   }
  );
 }
});

bunchOfCallbacks = new Observer();
bunchOfCallbacks.appendCallback(function(){alert('second');});
$('anything').observe('anyEvent', bunchOfCallbacks.runCallbacks);
bunchOfCallbacks.prependCallback(function(){alert('first');});