How to apply debouncer on change function jQuery? - javascript

How would one apply debouncer on this jQuery function. So far it makes no call.
$('.make-ajax-call-js').on($.debounce('change', function (e) {
//whatever ajax call
}));
I have debouncer script included in my js files.

Try like this:
$('.make-ajax-call-js').change($.debounce(1000, function(e) {
console.log("It works!");
}));

To fix this, you will have to pass in the debouncing function as a parameter to the jquery click event along with the debounce time
$('.make-ajax-call-js').click($.debounce(250, function(e) {
//whatever ajax call
}));

Related

Cannot get _.debounce() to work

I am having trouble trying to get underscore.debounce() to work. I am attaching a keydown event listener on an input field. I will perform some actions, then call debounce() which is not being called. I am wondering why it is not working?
I have provided two samples. The first one where I have not attached _.debounce() as inline is not working. The second one where I have attached _.debounce() as inline is working. I do not understand why the non-inline solution is working?
// This example does not ever call _.debounce()
$('input').on('keydown', onKeyDown);
function onKeyDown() {
console.log('performing some actions...');
_.debounce(function() {
console.log('debouncing'); // never called
}, 500);
}
// This example does call _.debounce()
$('input').on('keydown', _.debounce(function() {
console.log('debounce');
}, 500));
Debounce returns a function that will need to be invoked, in this case you are creating a function but never invoking it. Try this:
// This example does not ever call _.debounce()
var debounced = _.debounce(debounceStuff, 500);
$('input').on('keydown', onKeyDown);
function onKeyDown() {
console.log('performing some actions...');
debounced();
}
function debounceStuff() {
console.log('debouncing');
}

Javascript : Replace Event Listener

I am listening to an event and want to call different methods. For example, I am listening to animation end event and the code is something like this:
this.inAnimationCallback = function() {
console.log('In');
_this.elem.className = _this.settings.className;
};
this.outAnimationCallback = function() {
console.log('Out');
_this.elem.parentNode.removeChild(_this.elem);
};
this.elem.addEventListener(animationEvent, this.inAnimationCallback);
setTimeout(function() {
_this.elem.addEventListener(animationEvent, _this.outAnimationCallback);
// Call some animation here.
}, 3000);
What happens here is that instead of replacing the method attached to the event, JS adds the method and when animation ends, both methods are called. Console looks like this:
(2) In
Out
I'm writing this answer for those like me, who is just started learning JS. And this thread came up first in google to "js replace event listener"..
Although, I am not disagreeing with the answers to use removeEventListener(), but mozilla warns that this function is not always successful. So use it with care. not willing to go that road i have found two other ways to do it.
Use something like GlobalEventHandlers which is simple as target.onclick = functionRef;. Mozilla even warns:
Only one onclick handler can be assigned to an object at a time.
Within listener function add external function call to action function, and then replace reference to another external action function. For example this code will call firstAction(), then seconAction(), then first again...:
const buttonOne = document.getElementById('buttonOne');
buttonOne.addEventListener('click', listenerFunction);
let doAction = firstAction; //assigning doAction to firstAction
function listenerFunction() {
doAction(); //external function call
}
function firstAction() {
doAction = secondAction; //assigning doAction to secondAction
console.log('first action clicked');
}
function secondAction() {
doAction = firstAction; //assigning doAction to firstAction
console.log('second action clicked');
}
<button type="button" id="buttonOne" name="button">button1</button>
I wrote this answer to broaden solution scope: would have saved at least 6 hours of my time. If I had this in the first place...
You can just remove the event listener before adding the new one :
setTimeout(function() {
_this.elem.removeEventListener(animationEvent, _this.inAnimationCallback);
_this.elem.addEventListener(animationEvent, _this.outAnimationCallback);
// Call some animation here.
}, 3000);

jquery change event callback

How to call a function once after change() event complete?
for example, something like this: ( I know jQuery Doesn't have callback method as default )
$('#element').change( function(){
// do something on change
// $('#milestonesSelect').multiselect({ minWidth: 120 , height : '200px' ,selectedList: 4 }).multiselectfilter();
// some animation calls ...
// ...
}, function(){
// do something after complete
alert('another codes has completed when i called');
}
);
Is it possible to call a single callback after all the codes on change method done, except call a complete callback for every functions on it?
I need to do something after the change event has completed
Shall I need to set order to methods in change handler?
You can probably make use of event bubbling and register a callback in the document.
$(document).on('change', '#element', function(){
console.log('after all callbacks')
});
Demo: Fiddle
I just spent some time exploring this myself, and decided to submit my answer to this question as well. This is not utilizing any of jQuery's deferred methods, which might be a better approach. I haven't explored them enough to have an opinion on the matter.
$("#element").change(function() {
handler().after(callBack($("#element").val()));
}
function handler() {
alert("Event handler");
}
function callBack(foo) {
alert(foo);
}
Demo: JSFiddle
If I understand your question correctly, this will execute code only one time after a change event is fired:
var changed = false;
$('#element').on('change', function() {
if ( !changed ) {
// do something on change
changed = true;
}
}
});

How to fire an event immediately?

I'm binding an event like this, using prototype js:
$('country').observe('change',function(e) { ... });
How can I fire it once immediately?
in jQuery, I'd just tack on a .triggerHandler('change'). Is there something similar in prototype?
Use the load event. Something like this:
// calls addListeners when the document loads
Event.observe(window, 'load', addListeners, false);
function addListeners() {
// called onLoad
fireOnce();
// observer for the country dropdown
$('country').observe('change', function(event) {
fireOnChange();
});
}
function fireOnce() {
// do something
}
function fireOnChange() {
// do something
}
When the document loads, fireOnce() will execute. I use this technique all the time.
If using an extension is an option, I have had success in the past with event.simulate for this purpose.
It'll allow you to do something like:
$('country').simulate('change');
Try this:
var handler = function(e) {...};
$("country").observe("change",handler);
handler();
Alternatively (less readable, avoids temporary variable):
$("country").observe("change",(function(e) { ... return arguments.callee;})());
However, in both cases you will not be able to use this as you might expect. This solution is better suited to more general callbacks such as for setInterval
...if you know that it exists, and you know that you're not waiting for pageload or waiting for a script to load, why not just:
(function (el) {
if (!el) { return; }
doSomething(el);
}(document.getElementById("country")));

Automatic call of on-click function in jquery

I am looking to call a onclick function forcefully.
$('.checkbox-selector').click(function() {
});
$('.checkbox-selector1').click(function() {
});
When a control goes to the first function, the second function should be called automatically
i.e. onlick event is triggered.
function func1(e) {
// do stuff for selector
// run func2 too!
func2();
}
function func2(e) {
// do stuff for selector1
}
$('.checkbox-selector').click(func1);
$('.checkbox-selector1').click(func2);
Is this what you mean?
If so, make sure to look at the comments! They contain quite valuable information considering events and such.
You can replace func2(); with $('.checkbox-selector1').trigger('click'); to trigger the native event handler too! Using $('.checkbox-selector1').triggerHandler('click'); is practically the same as func2();, whichever you prefer.
Take a look at the jQuery trigger function
Not sure what it is exactly you're looking for, but I'd guess:
$('.checkbox-selector').click(function() {
/* all sorts of stuff*/
$('.checkbox-selector1').click();
//or:
$('.checkbox-selector1').trigger('click');
});
$('.checkbox-selector1').click(function() {
});
Something like that?

Categories