Calling this inside setTimeout - javascript

I Am looking for a way to proper call this inside function now i have quick hack var that = $(this); but i am sure that there is propper way of doing it. How i can avoid this hack?
This is input field which i use to get var and inspect Typing Interval
<input type="text" data-package="pink" class="js-p-input">
this i my code:
var cCalc = (function ($) {
var s;
return {
settings: {
typingTimer: "",
doneTypingInterval: 300,
$inputs: $(".js-p-input"),
},
init: function () {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function () {
//on keyup, start the countdown
s.$inputs.on('keyup', function () {
var that = $(this);
clearTimeout(s.typingTimer);
s.typingTimer = setTimeout(function() {
cCalc.doneTyping(that, that.data("package"));
}, s.doneTypingInterval);
});
s.$inputs.on('keydown', function () {
clearTimeout(s.typingTimer);
});
},
doneTyping: function ($input, packageName) {
console.log('done!');
cCalc.getValues($input.val(), packageName);
},
};
})(jQuery);
cCalc.init();

There is nothing wrong with using that "hack", it is standard operating procedure. See also here What is the difference between call and apply? for even more "hacky" stuff with "this" that is standard.

As others have pointed out, there's not really anything wrong with using a closure but you could alternatively bind "this" into the timeout function scope like so:
s.$inputs.on('keyup', function () {
clearTimeout(s.typingTimer);
s.typingTimer = setTimeout(function() {
cCalc.doneTyping($(this), $(this).data("package"));
}.bind(this), s.doneTypingInterval);
});

Related

assigning variable inside jquery on or javascript bind

Short question, how can I more efficiently write below code so I don't repeatedly assign the parent variable a new value?
Is this bind function the same as using object literals?
function bindAuthorPopup() {
$(".insight-author").on({
mouseenter: function (event) {
var parent = $(this).parent('div').find('.popup-content');
parent.toggleClass('show');
},
mouseleave: function (event) {
var parent = $(this).parent('div').find('.popup-content');
parent.toggleClass('show');
},
});
}
You can do something like this:
function bindAuthorPopup() {
$(".insight-author").each(function() {
var elem = $(this);
var parent = elem.parent('div').find('.popup-content');
elem.on({
mouseenter: function (event) {
parent.toggleClass('show');
},
mouseleave: function (event) {
parent.toggleClass('show');
},
});
});
}
This works even if the callbacks are different. If they're always the same, then you can use what #sh1da9440 wrote.
You can pass space-separated event types to the "on" method.
function bindAuthorPopup() {
$(".insight-author").on('mouseenter mouseleave', function (event) {
var parent = $(this).parent('div').find('.popup-content');
parent.toggleClass('show');
});
}

Cloning $(this) in a javascript object?

I'm learning how to use objects to help organize my code and give it some structure but I've run into a problem. I don't understand how to set the $(this) from inside of one function to the $(this) of another function.
I'm researching call and apply but I can't seem to grasp how it works in this scenario.
cloneCard and clickCard is where I'm having the problem. I want to pass the $(this) that is referenced when I click the card to the cloneCard function.
Here is my code so far (updated to reflect the answer):
var Modal = {
init: function(config) {
this.config = config;
this.clickCard();
this.removeModal();
this.clickOutside();
this.createClose();
},
clickCard: function() {
$this = this;
this.config.boardOutput.on('click', '.card', function(event) {
$this.showOverlay();
$this.cloneCard.call($(this));
$this.createClose();
});
},
cloneCard: function() {
this.clone()
.replaceWith($('<div/>').html(this.html()))
.removeClass('card')
.addClass('modal')
.css("margin-top", $(window).scrollTop())
.prependTo('body');
},
showOverlay: function() {
this.config.overlay.show();
},
removeModal: function() {
$('.modal').remove();
$('.overlay').hide();
},
clickOutside: function() {
this.config.overlay.on('click', this.removeModal);
},
createClose: function() {
$('<span class="close">X</span>')
.prependTo('.modal')
.on('click', this.removeModal);
}
};
Modal.init({
boardOutput: $('#board-output'),
overlay: $('.overlay')
});
For what you need, calling self.cloneCard.call($(this)); instead of self.cloneCard($(this));
should work. What you're doing is, calling cloneCard passing it the element in which the the clickCard event occured.
If this doesn't work, i think we'll need more information to sovle your problem.

jQuery click event not working while using "Module Pattern"

I'm an intermediate front-end JS developer and I'm trying the Module Pattern outlined by Chris Coyyer here.
But when I store a jQuery selector in the settings, I'm unable to use it to trigger a click event. See the below code with my comments... Any help is greatly appreciated!
var s,
TestWidget = {
settings: {
testButton: $("#testing")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
console.log(s.testButton); // This works: [context: document, selector: "#testing", constructor: function, init: function, selector: ""…]
//This doesn't work - why?????
s.testButton.click(function() {
//Why isn't this triggered?
alert('testButton clicked');
});
/*This works, obviously:
$('#testing').click(function() {
alert('testButton clicked');
});
*/
}
};
$(document).ready(function() {
TestWidget.init();
});
The problem is that you initialize $("#testing") before the DOM is ready, so this jQuery object is empty.
A simple solution is to put all your code in the ready callback.
Another one would be to replace
settings: {
testButton: $("#testing")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
with
settings: {
},
init: function() {
s = this.settings;
s.testButton = $("#testing");
this.bindUIActions();
},
But it's hard to get why you use so much code for such a simple thing. You might be overusing the pattern here and it's not really clean as you have two global variables s and TestWidget when one would already be a lot.
Here's a slight variation of your code which would be, in my opinion, cleaner, while still using modules (IIFE variant) :
TestWidget = (function(){
var settings = {};
return {
init: function() {
settings.testButton = $("#testing");
this.bindUIActions();
},
bindUIActions: function() {
console.log(settings.testButton);
settings.testButton.click(function() {
alert('testButton clicked');
});
}
}
})();
$(document).ready(function() {
TestWidget.init();
});
settings is kept in the closure and doesn't leak in the global namespace. Note that even this version doesn't make sense if you don't do more with the module.

Function being run when bind in jquery document ready

I'm trying to bind a click event to the function below, however the entire function is currently being run when being binded in the document ready.
Is it possible to run it solely on the click event? Possibly it has something to do with the way my method is composed?
Thanks in advance
$(function() {
$("#expand-search").on("click", search.resize());
});
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState());
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
You are calling the function (handler) instead of passing the reference (name) of function (handler) to on().
Change
$("#expand-search").on("click", search.resize());
To
$("#expand-search").on("click", search.resize);
No parenthesis to event handlers! You want to pass the function-to-be-executed, not the result from executing it. Also, you will need to move your search object inside the ready handler since you use selectors for its initialisation.
$(function() {
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState);
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
$("#expand-search").on("click", search.resize);
});

dojo.hitch() scope for window.setInterval()

I am trying to produce a blinking effect using dojo fadeIn/Out.
The following snippet of code is defined inside the declaration of a widget class:
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
window.setInterval ( function() {
dojo.fadeOut(
{
node: this._headerDiv.domNode,
onEnd: function() {
dojo.fadeIn({node: this._headerDiv.domNode},3000).play();
}
},3000).play();
}, blinkInterval);
},
_highlightEffect : function() {
this.func = dojo.hitch(this,this._startHighlightEffect);
this.func();
}
The problem I am facing is that it says,"this._headerDiv is undefined". On checking with firebug, the scope of this._headerDiv is Window instead of the parent widget.
Please help me understand what am I missing here.
What #jbabey describes will work, but in terms of dojo.hitch, you used it on the wrong function. You need to hitch the function that is passed into setInterval.
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
// hitch the function that will be executed by the setInterval call *********
window.setInterval (dojo.hitch(this, function() {
dojo.fadeOut(
{
node: this._headerDiv.domNode,
onEnd: dojo.hitch(this, function() {
dojo.fadeIn(
{node: this._headerDiv.domNode},3000).play();
})
},3000).play();
}, blinkInterval));
},
_highlightEffect : function() {
this._startHighlightEffect();
}
you can save the context when it is the context you want, and use it later:
_startHighlightEffect : function() {
var blinkInterval = 5000; //Scope here is that of the parent widget
var that = this; // save the scope
window.setInterval ( function() {
dojo.fadeOut(
{
node: that._headerDiv.domNode, // use the saved scope
onEnd: function() {
dojo.fadeIn({node: that._headerDiv.domNode},3000).play();
}
},3000).play();
}, blinkInterval);
}

Categories