views:

61

answers:

1

I'm using dojo. I've got something like this:

<a id="fooBar" onclick="foo();bar();">Foo then Bar</a>

I want to trigger fooBar's click handler from another button. Something like:

<a onclick="dojo.query('#fooBar')[0].click()">Do FooBar</a>

Can I do that?

+1  A: 
dojo.byId('fooBar').onclick();

or

dojo.query('#fooBar')[0].onclick();

See examples.

I haven't used Dojo before, but can safely say that you can do better than inline events :). Moreover, these will not be managed by Dojo as they were added inline. The onclick method here is a native DOM method for triggering the function attached to the onclick property of the element.

dojo.byId is a shortcut to document.getElementById, and honestly you can easily do without Dojo here:

document.getElementById("fooBar").onclick();

Here's the three methods with a comparison of character savings (9 and 14):

document.getElementById('fooBar').onclick();
dojo.query('#fooBar')[0].onclick();123456789
dojo.byId('fooBar').onclick();12345678901234

See a couple of good reasons for not using inline click handlers.

Anurag
well stated, though dojo.byId does a tad bit of work working around form/id/name mishaps, so isn't quite a straight alias. There is a function in a mini project of mine to trigger native and custom dom events (dojo.trigger('foobar', "click")) but even that is more expensive than just calling the click function. ideally, one would bind a named/namespaced click function to a node via attachEvent/addEventListener (dojo.connect), and simply call that function directly rather than touching the dom at all. In Dojo we have dojo.publish and dojo.subscribe for a pattern based on that concept.
dante