alonisser
alonisser

Reputation: 12068

how to pass event to function in bind event - jquery mobile

I have a function SomeFunction(event) - I want to bind a 'tap' event to a ('#selectorid') element, and I want to know what is the right syntax:

should I use:

 $('#selectorid').unbind().bind('tap',SomeFunction);   

or:

  $('#selectorid').unbind().bind('tap',function(event){
    SomeFunction(event);});});

or:

 $('#selectorid').unbind().bind('tap',function(){
       SomeFunction(event);}); 

or

$('#selectorid').unbind().bind('tap',SomeFunction(event));   

I'm getting completely mixed up about this and would be glad for some clarification..

I'm using the lateset rc2 jquery mobile

Upvotes: 2

Views: 1989

Answers (1)

b01
b01

Reputation: 4384

#1 should get the job done, but requires that you have "SomeFunction" defined globally:

$( "#selectorid" ).unbind().bind( "tap", SomeFunction );

What will happen is when the event is fired, it will call same "SomeFunction" and pass the event as it's first parameter, So all you have to do is define SomeFunction, like so:

SomeFunction( p_event )
{
  // Do cool evil stuff with the event parameter like cancel the tap event >:)
  p_event.preventDefault();
  // That's it. :)
}

#2 will also work, but again, will require "Somefunction" to be defined globally.

$( "#selectorid" ).unbind().bind( "tap", function(p_event)
{
    SomeFunction( p_event );
});

What will happen in the case of #2, is that the anonymous function will call the "SomeFunction" and pass along the event, just like in the first example, but with an extra step. Which is why I prefer the first method. :)

#3 and #4 have errors and are just bad version of the previous two.

Also, what I mean by globally defined, is that the "SomeFunction" is available everywhere on the page, and not just defined in an object, plugin, or closure. Because if it were, then calling it in your event handler may produce undefined errors. If your wondering, I like to use double quotes with my strings and pre-pend my parameter variables with 'p_', so I can use the same variable name in the function, and easily distinguish between the two. It my personal naming convention. :)

Upvotes: 2

Related Questions