16

I was wondering how to programmatically fire a change event with YUI3 -- I added a change listener to one select box node:

Y.get('#mynode').on('change', function(e) {
 Alert(“changed me”);
});

and somewhere else in the script want to fire that event. It works, of course, when a user changes the select box value in the browser. But I've tried many ways to fire it programmatically, none of which have worked. Including:

// All below give this error: T[X] is not a function (referring to what's called in .invoke(), // in the minified javascript
Y.get('#mynode').invoke('onchange');
Y.get('#mynode').invoke('change');
Y.get('#mynode').invoke('on','change');
Y.get('#mynode').invoke("on('change')");


/* Tried using .fire() which I found here: 
* http://developer.yahoo.com/yui/3/api/EventTarget.html#method_fire
* Nothing happens
*/

Y.get('#mynode').fire('change'); 

/* Looking around the APIs some more, I found node-event-simulate.js: 
 * http://developer.yahoo.com/yui/3/api/node-event-simulate.js.html, 
 * which by its name would seem to have what I want. I tried:
 * Error: simulate(): Event 'change' can't be simulated. 
 * ( (function(){var I={},B=new Date().getTim...if(B.isObject(G)){if(B.isArray(G)){E=1;\n)
 */

Y.get('#mynode').simulate('change');

Any help would be appreciated!

David Underhill
  • 15,896
  • 7
  • 53
  • 61
atp
  • 30,132
  • 47
  • 125
  • 187

3 Answers3

12

YUI 3.0 does not support simulating the change events, as you've discovered. However it will be supported in YUI 3.1. It is in the trunk now.

Your third attempt:

Y.get('#mynode').simulate('change');

should work in 3.1.

edit

It looks like you can just replace the YUI 3.0 version of event-simulate.js with the trunk version, and it will work in an otherwise 3.0 app. I haven't seen any issues so far.

Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99
6

The usual solution is not to programmatically fire the event, but rather move all the event logic to a function, and instead call that function from your code where appropriate.

Y.get('#mynode').on('change', function(e) {
    AlertUserOfChange();
});

function AlertUserOfChange()
{
    Alert(“changed me”);
}
Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
  • Yeah, that's how I normally do it but I really wanted to know if it was possible. I guess it isn't. – atp Aug 03 '09 at 20:42
  • 1
    `Y.get('#mynode').on('change', AlertUserOfChange);` is all you need. Then add the param e to AlertUserOfChange, like so `function AlertUserOfChange(e)` – imns Apr 21 '11 at 20:33
-1

How about this

Y.Event.simulate('#mynode', 'change');
SolutionYogi
  • 31,807
  • 12
  • 70
  • 78