attach one observer for many events to an element

15 views
Skip to first unread message

buda

unread,
Dec 17, 2009, 9:03:32 AM12/17/09
to Prototype & script.aculo.us
What is the best way to attach one observer to many events
for examle: I need to attach an observer to input element to validate
input value for 'change' and 'paste' events


T.J. Crowder

unread,
Dec 17, 2009, 10:40:09 AM12/17/09
to Prototype & script.aculo.us
Hi,

Just reuse the same handler for multiple events:

function handler(event) { /* ... */ }

element
.observe('change', handler)
.observe('paste', handler);

If you need to bind, do that first so you're not creating unnecessary
extra functions:

var Thingy = Class.create((function() {

function handler(event) { /* ... */ }

function hookUsUp(element) {
var boundHandler = handler.bind(this);
element
.observe('change', boundHandler)
.observe('paste', boundHandler);
}

return {hookUsUp: hookUsUp};
})());

HTH,
--
T.J. Crowder
Independent Software Consultant
tj / crowder software / com
www.crowdersoftware.com

buda

unread,
Dec 17, 2009, 4:09:00 PM12/17/09
to Prototype & script.aculo.us
thanks for samples

> > input value for 'change' and 'paste' events- Скрыть цитируемый текст -
>
> - Показать цитируемый текст -

Alex Wallace

unread,
Dec 17, 2009, 5:36:05 PM12/17/09
to prototype-s...@googlegroups.com
A faster method would be to attach a single observer for all of the inputs. Something like:

var InputsObserver = Class.create({

initialize : function(){
  $("input-wrapping-element").observe("click",
    this.inputsClickHandler.bindAsEventListener(this));
},

clickHandler : function(event){
  var input = event.findElement("input");
  if (input)
    this.inputChangeHandler(input);
},

inputChangeHandler : function(input){
  if (input.checked) { } // etc...
}

});

2009/12/17 buda <www...@pochta.ru>

--

You received this message because you are subscribed to the Google Groups "Prototype & script.aculo.us" group.
To post to this group, send email to prototype-s...@googlegroups.com.
To unsubscribe from this group, send email to prototype-scripta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/prototype-scriptaculous?hl=en.



Reply all
Reply to author
Forward
0 new messages