jQuery .on() method with multiple events - passing argument to event handler function - javascript

Here is the code :
$('.el')
.drag("init", function () {
//
})
.drag("start", function () {
//
})
.drag("end", function () {
//
});
I couldnt find a way to pass the parameters in the case below
$('.el').on({
drag: function(){
//*init* functions
},
drag: function(){
//*start* functions
},
drag: function(){
//*end* functions
}
})
Is it possible to pass parameters while using on event delegation for multiple events at once. Or the only solution is using on for multiple times.

You should probably lead with the fact that you're using a plugin, more specifically this plugin.
The docs are pretty clear, there are events built in, such as draginit, dragend etc. that can be used instead of the drag() method
$(document).on({
draginit: function(){
//*init* functions
},
dragstart: function(){
//*start* functions
},
dragend: function(){
//*end* functions
}
}, '.el');

Related

2 different on click events conflict?

I have one link:
link
And I have two different onclick function set to the two classes like this:
jQuery(".lorem").each(function(){
this.onclick = function() {
// stuff
}
});
and
jQuery(".hello").each(function(){
this.onclick = function() {
// stuff
}
});
This stops the top one to work. Why? And how can I make both functions work while being separated?
You can only assign one function to the onclick property. You should use normal jQuery event binding, it allows multiple handlers:
$(".lorem").click(function() {
// stuff
});
$(".hello").click(function() {
// stuff
});
If you want to do it with native Javascript, you can use addEventListener; as the name suggests, these are additive, they don't replace.
jQuery(".lorem").each(function(){
this.addEventListener("click", function() {
// stuff
})
});
jQuery(".hello").each(function(){
this.addEventListener("click", function() {
// stuff
})
});
When you are using query, why use .onclick on the DOM element (therefore overwriting the previous binding). Instead use jQuery's .on:
$('.lorem').on('click', function(){
// something
});
$('.hello').on('click', function(){
// something else
});

Jquery executing/triggering same code on different events

I have this function onclick event of custom tag densitybtn='yes'
$("[densitybtn='yes']").on('click', function () {
var no_of_people = 0;
//calcdensity
$("[calcdensity='yes']").each(function () {
no_of_people = parseInt($(this).val()) + no_of_people;
});
var total_density = parseInt(carpetArea) / parseInt(no_of_people);
$("#densityVal").html(Myval);
});
Can i extend same code by extending it to $("[calcdensity='yes']").on('blur')
$("[calcdensity='yes']").on('blur').$("[densitybtn='yes']").on('click', function () {
});
Am not sure on executing same code on different events
Let me know is this method correct? or is there any alternative way available?
Define the function normally (not as an anonymous function) and pass the function to the event listeners
function listener() {
var no_of_people = 0;
//calcdensity
$("[calcdensity='yes']").each( function() {
no_of_people = parseInt($(this).val())+no_of_people;
});
var total_density = parseInt(carpetArea)/parseInt(no_of_people);
$("#densityVal").html(Myval);
}
$("[densitybtn='yes']").on('click', listener);
$("[calcdensity='yes']").on('blur', listener);
Nope, thats not a good practise.
Instead you can write a function for the second intent and call it on blur of $("[calcdensity='yes']").
You can bind multiple events using jQuery's .on() method by space-separating the event arguments.
$("[densitybtn='yes']").on('click blur', function() {
// actions to perform
})
You can bind events to multiple elements using jQuery's .add() method.
$("[densitybtn='yes']").add("[calcdensity='yes']").on('click blur', function() {
// actions to perform
})

Attach a jquery event after object is created

I am using the bPopup jquery library.. the syntax to add to the onclose event is pretty straightforward:
$('element_to_pop_up').bPopup({
onOpen: function() { alert('onOpen fired'); },
onClose: function() { alert('onClose fired'); }
})
What I want to do is add something to the onClose event after the object is created.. is it possible?
In general you can do this by creating a function that you fiddle with later:
var myOnClose = function() { alert('onClosed fired'); }
function doOnClose() { myOnClose(); }
$('element_to_pop_up').bPopup({
onOpen: function() { alert('onOpen fired'); },
onClose: doOnClose
})
// later...
myOnClose = function() { console.log("Doing something different!"); }
You can access the bPopup object which will be present inside the data of the element.
$('element_to_pop_up').bPopup({
onOpen: function() { alert('onOpen fired'); },
onClose: function() { alert('onClose fired'); }
});
$('element_to_pop_up').data('bPopup');
NOTE: There is no guarantee that the created object will be always present in element's data. But this is widely used approach. It is better to rely on the callback provided.
var realOnclose = f1;
function myOnClose(){realOnclose();}
$('element_to_pop_up').bPopup({
onOpen: function() { alert('onOpen fired'); },
onClose: myOnClose
})
function f1() { alert('onClose fired'); }
function f2() { alert('hey I am another function'); }
//when you want to change the action when onclose...
realOnclose = f2;
If you want to add to, rather than replace, the code you originally supply to the onClose option, you could trigger a custom event:
$('element_to_pop_up').bPopup({
onClose: function() {
// Do the original stuff here.
this.trigger('popup:close');
}
});
Then, at any time later, you can register a handler for the custom event:
$('element_to_pop_up').on('popup:close', function() {
// Do the additional stuff here.
});
Note: Looking at the code for the bPopup library, it looks like the context for the onClose function is the original jQuery object, but if it isn't, replace with: $('element_to_pop_up').trigger('popup:close');.

JQuery Plugin - triggering internal functions by callback

Skip to bottom for question
JQuery plugin:
$.fn.myPlugin = function( options ) {
var options = $.extend({
myOption: true,
edit: function() {},
done: function() {}
}, options);
options.edit.call(this);
options.done.call(this);
//plugin guts removed to prevent over complication
return {
edit: function(obj) {
$(obj).closest('#myParent').find('#myInput').autosizeInput(); //plugin to autosize an input
},
done: function(obj) {
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
}
}
});
Bear in mind this is a cut down version of my plugin.
Called from page:
$(document).ready(function() {
var myPlugin = $('.editable').myPlugin({
edit: $(this).on('click', '.edit-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.edit( $(this) ); //call the edit returned function
}),
done: $(this).on('click', '.done-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.done( $(this) ); //call the done returned function
});
});
});
This works great for the most part, however, what i really want is have functions called from inside my plugin every time a specific callback is triggered - without the need to call from outside the plugin.
I have tried including delegated events in my plugin:
$(this).on('click', '.edit-td', function(e) {
e.preventDefault();
$(this).closest('#myParent').find('#myInput').autosizeInput();
});
$(this).on('click', '.done-td', function(e) {
e.preventDefault();
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
});
But when the .edit-td is triggered it propagates and triggers the .done-td event, if i put e.stopPropagation() in the edit-td function (because it has been delegated) edit-td stops firing completely.
And non-delegated method:
$(this).find('.done-td').click(function(e, this) {});
But I can't parse the returned object (this) to the internal function before the internal function has completed. (just comes up undefined or missing formal parameter).
*Skip to here
To avoid the question becoming to localised -
I need to have functions called from inside my
plugin every time a specific callback is triggered.
Without calling it using closures
Something like:
if( $.fn.myPlugin.callback().is('edit') ) {
//fire function
}
I needed to return a function(s) like so:
return {
enable: function(arg) {
//do something
},
disable: function(arg) {
//do something
}
}
That way I can call it from inside my plugin by referencing itself like this:
this.myPlugin().disable();

Using variable for selectors in events

for some reason I need to use a variable as the selector for events in backbone, but I can't figure how to do this :
app.views.Selfcare = Backbone.View.extend({
events: {
click window.parent.document .close : "closeWindow"
},
closeWindow: function() {
//code
}
});
I have to use a different scope and I can't do "click .close" : "closeWindow".
Thx for your help.
I had a look at Backbone.js's source code and found out that if your view's events is a function then the function is called and it's return value is used as the events object.
This means that your code can be changed like this:
app.views.Selfcare = Backbone.View.extend({
events: function() {
var _events = {
// all "standard" events can be here if you like
}
_events["events" + "with variables"] = "closeWindow";
return _events;
},
closeWindow: function() {
//code
}
});
THIS is the interesting part of the source code:
if (_.isFunction(events)) events = events.call(this);
Update:
Example is available on JSFiddle HERE**
I'm not sure that you'll be able to use a variable there. You could use the built-in Events methods (see documentation) to add a custom listener, then add an event listener to window.parent.document to trigger that custom event (use the Events.trigger method).
That said, it would be much easier to decouple this event from Backbone entirely (unless you don't want to do that), and go down the addEventListener route:
app.views.Selfcare = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'closeWindow');
if(this.options.clickTarget) {
this.options.clickTarget.addEventListener('click', this.closeWindow, false);
}
},
render: function() {
// Render to the DOM here
return this; // as per Backbone conventions
},
closeWindow: function() {
// Stuff here
}
});
// Usage:
var mySelfcare = new app.views.Selfcare({
clickTarget: window.parent.document
});
I think that should work, although I haven't tested it (and there may be one or two syntactical errors!)

Categories