jQuery - using methods for custom events - javascript

I have a custom jQuery event like this
jQuery(this).trigger({
type: 'my_own_event',
data1: 'foo',
data2: 'bar'
});
To attach an event handler I have to use the .on() function like this.
jQuery(element).on( 'my_own_event', function(e) {
//Do something
});
How do I use it like any other inbuilt event like .click(), .keyup(). Something like this
jQuery(element).my_own_event(function(e){
//Do Something
});
I tried using jQuery.fn to do this as follows
jQuery.fn.my_own_event = function(callback) {
jQuery(this).on('my_own_event',callback);
}
and it does work on Firefox 27.
Is this the right way to do this?
Is it OK to use underscores in the event name?

That's fine. The naming is okay, merely a matter of convention.
You should tweak the shortcut function, though. The jQuery() is not required, as this is already a jQuery object. You should also return the original object for chaining purposes.
You may also want to handle the empty argument version of the call, as the builtin event shortcuts do, to trigger the event.
Here's how the jQuery source itself does it:
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
Where name is the event such as click or keyup. This also handles the optional data argument, which would set event.data in the callback function.
Then you're completely in line with the existing jQuery event shortcut function conventions.
So your example could be changed to:
jQuery.fn.my_own_event = function(data, callback) {
return arguments.length > 0 ?
this.on('my_own_event', null, data, callback) :
this.trigger('my_own_event');
};

Yes the Custom event you have created is fine and the event name is also as per standard event naming convention
Article from official Jquery site:
the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers. Event names should only contain alphanumerics, underscore, and colon chraracters.
REF:
https://api.jquery.com/trigger/
Happy Coding:)

Related

Is it possible to get the event name thats been triggered so I can use it as a string in my method?

I'm wondering if I run Backbone.Events.trigger('show:something', this.model); can I get that event name to pass to method I'm mapping to in my subscribed listener this.listenTo(Backbone.Events, 'show:something', this.toggle, this);
toggle: function(param) {
// can I get show:something?
}
Short answer no.
However you can listen to the 'all' event, and the name of the event will be passed to the function as the first param.
this.on('all', function(ev, ...) {
console.log(ev); // the name of the event - show:something in your above example
});
No you cannot as the only event trigger with this is all as joe fitter described source http://backbonejs.org/docs/backbone.html
But other option is to bind the function you want to be called instead of using the raw function. For example if you are using underscore use this instead of this.toggle
_.bind(this.toggle, this, 'theEventNameYouWant');
and let toggle first parameter be
toggle: function(eventName, param) {
source http://underscorejs.org/#bind
I am not sure how if you need the second this for the listenTo bind. Get back to me and I will update answer.

Binding/listening to events

I made a jQuery plugin that calls its functions at timed events. I want to provide those who use the plugin the ability to listen to these functions when they are called and add code to be performed when the functions are triggered.
This may be a simple question but I can’t wrap my head around it. What is the best method to achieve this? I can only find information on binding handlers to events, not events to events. I want something like the code below:
$( "body" ).bind( "pluginInstance.functionName", function() {
console.log( "triggered" );
});
You could invoke the declared function you passed to the plugin. Example:
$.fn.myPlugin = function(callback){
callback();
}
$('elem').myPlugin(function(){
console.log("triggered");
})
If you wanted to be more sophisticated about it you could set the callback function to an object and refer to the object versus the arguments, which is more specific and easier to read:
$.fn.myPlugin = function(options){
options.callback();
}
$('elem').myPlugin(
var options = {
callback: function(){
console.log('triggered')
}
}
)
I would allow the plugin consumer to pass in an options hash to your plugin's constructor with optional event methods / properties that you have predetermined. I would also have a 'defaults' object defined in your plugin that defines those available properties and events that the user can override. You can use the jQuery extend method to copy any defaults that the user did not pass in within the constructor.
As an example, you may have a 'onSlide' event that the user can add a callback for in your plugin. I would set the plugin up as follows:
$.fn.newPlugin = function(options){
var defaults = {
onSlide: null,
onRightClick: null
};
var settings = $.extend(defaults, options);
//Pretend something in your plugin happens and you want to optionally
//invoke the user's passed in onSlide method if they set it
if(settings.onSlide != null){
settings.onSlide();
}
}
When the user is consuming your plugin they can pass the 'onSlide' handler into the constructor:
$('elem').newPlugin({
onSlide: function(){
alert('slide event triggered');
}
});
You can use custom events http://css-tricks.com/custom-events-are-pretty-cool/. See http://jsfiddle.net/3L45H/1 and https://learn.jquery.com/plugins/basic-plugin-creation/
From your plugin, you can call the following to trigger an event
$(this.element).trigger('pluginInstance.functionName');
And listen for it as you do any other DOM events
$('body').bind( "pluginInstance.functionName", function() {
console.log( "triggered" );
});
$('body').myPlugin();

What is passed with the bind in JS?

I am binding a select of a custom control to a function. I just want to clarify when I bind something like this
auditFileUpload.bind("select", uploadSelectfunction);
I know I can use the following function
uploadSelectfunction(e)
{
}
how is e getting passed? is it the events? or the object itself?
if I had a function like this, how would I bind it?
uploadSelectfunction(e, datatype)
{
}
auditFileUpload.bind("select", function() { uploadSelectfunction(events, "CSV" });
I tried events, it doesn't work..
sugesstions? clarifications?
The events parameter is simply the first parameter passed to the event handler/method. Just pass that on:
auditFileUpload.bind("select", function(events) { uploadSelectfunction(events, "CSV"
In the original version uploadSelectfunction is simply a pointer to a function that happens to take one argument. That events argument is defined inside the select event.
If you put an inline method instead (as you have done) you need to accept the events parameter, and pass it on to your code.

How to Pass Custom Parameters to Event Handler

Just getting started with Dojo. I want to pass a couple of custom parameters to an event handler. In jQuery, you can do it like this:
$('#button').click({
customData: 'foo'
}, handlerFunction);
And customData can be accessed from handlerFunction like this:
function handlerFunction(event) {
console.log(event.data.customData);
}
I'm migrating a bit of jQuery code over to Dojo. How can I pass those parameters to the Dojo event handler?
Well, generaly, closures allow you to pass "hidden" parameters to a function:
function make_event_handler(customData){
return function(evt){
//customData can be used here
//just like any other normal variable
console.log(customData);
}
}
So when connecting an event in dojo:
dojo.connect(node, 'onclick', make_event_handler(17));
Another possibility that I like a lot is using dojo.partial / dojo.hitch to create the closures for you.
function event_handler(customData, evt){
///
}
dojo.connect(node, 'onclick', dojo.partial(event_handler, 17))
Note that all of these these required your event handlers to be created with passing the extra parameter(s) in mind. I don't know if you can do a more direct translation of the JQuery code since that would require extra massaging of the evt variable and I don't think dojo does that.
Also:
this.connect(other, "onClick", function(e) {
/* other is accesible here still */
});
or :
this.connect(other, "onClick", dojo.hitch(this, "handler", other);
and its event handler:
this.handler = function(other, evt){...}

jQuery's .click - pass parameters to user function

I am trying to call a function with parameters using jQuery's .click, but I can't get it to work.
This is how I want it to work:
$('.leadtoscore').click(add_event('shot'));
which calls
function add_event(event) {
blah blah blah }
It works if I don't use parameters, like this:
$('.leadtoscore').click(add_event);
function add_event() {
blah blah blah }
But I need to be able to pass a parameter through to my add_event function.
How can I do this specific thing?
I know I can use .click(function() { blah }, but I call the add_event function from multiple places and want to do it this way.
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
You need to use an anonymous function like this:
$('.leadtoscore').click(function() {
add_event('shot')
});
You can call it like you have in the example, just a function name without parameters, like this:
$('.leadtoscore').click(add_event);
But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:
$('.leadtoscore').bind('click', { param: 'shot' }, add_event);
And access it in add_event, like this:
function add_event(event) {
//event.data.param == "shot", use as needed
}
If you call it the way you had it...
$('.leadtoscore').click(add_event('shot'));
...you would need to have add_event() return a function, like...
function add_event(param) {
return function() {
// your code that does something with param
alert( param );
};
}
The function is returned and used as the argument for .click().
I had success using .on() like so:
$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);
Then inside the add_event function you get access to 'shot' like this:
event.data.event_type
See the .on() documentation for more info, where they provide the following example:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.
//click handler
function add_event(event, paramA, paramB)
{
//do something with your parameters
alert(paramA ? 'paramA:' + paramA : '' + paramB ? ' paramB:' + paramB : '');
}
//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});
//or use variables
var a = 'first',
b = 'second';
$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});
$imgReload.data('self', $self);
$imgReload.click(function (e) {
var $p = $(this).data('self');
$p._reloadTable();
});
Set javaScript object to onclick element:
$imgReload.data('self', $self);
get Object from "this" element:
var $p = $(this).data('self');
I get the simple solution:
<button id="btn1" onclick="sendData(20)">ClickMe</button>
<script>
var id; // global variable
function sendData(valueId){
id = valueId;
}
$("#btn1").click(function(){
alert(id);
});
</script>
My mean is that pass the value onclick event to the javascript function sendData(), initialize to the variable and take it by the jquery event handler method.
This is possible since at first sendData(valueid) gets called and initialize the value. Then after jquery event get's executed and use that value.
This is the straight forward solution and For Detail solution go Here.
Since nobody pointed it out (surprisingly). Your problem is, that $('.leadtoscore').click(add_event); is not the same as $('.leadtoscore').click(add_event('shot'));. The first one passes a function, the second a function invocation so the result of that function is passed to .click() instead. That's not what you want. Here's what you want in vanilla JavaScript terms:
$('.leadtoscore').click(add_event.bind(this, 'shot'));
Function.prototype.bind() passes the function to .click() just like in the first example but with bound this and arguments that will be accessible on invocation.

Categories

Resources