jQuery - undefined function call on click - javascript

I want to call a function on the click event, my collegue defined the function as written below. Somehow I cannot access it, what is wrong?
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
});
}

this in a click function is the clicked element. Save a reference of the object in a variable outside the function and use it :
function Start(data) {
var self = this; //HERE
this.move= function() {
....
};
$('.button').click(function(){
self.move();
});
}
Here's an article that may give you more explanation about the above fix.

try this, you must remember reference to your main function.
function Start(data) {
var that = this;
this.move = function() {
....
};
$('.button').click(function(){
that.move();
});
}

Another way to keep the scope is to use jQuery's proxy()
$('.button').click($.proxy(this.move, this));

In an event handler bound with jQuery, this refers to the DOM element on which the handler was bound. See jQuery Event Basics.
You can override jQuery's this binding by using function#bind on the click handler:
function Start(data) {
this.move= function() {
....
};
$('.button').click(function(){
this.move();
}.bind(this));
}
Beware of browser support for function#bind -- if you target older browsers you'd need a polyfill or simply assign the value of this to another variable.

Related

How to reference "this" of another parameter passed into function?

Say I have a javascript function for a hover event like this:
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
AnimatedElement.hide();
}
});
}
The tricky part is I want to keep AnimatedElement dynamic, and be able to use it as a reference of HoverElement's "this".
Here's an example of how I'd want AnimatedElement to function:
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}
});
}
So I'd like AnimatedElement to be able to be a "this" reference to HoverElement. I've tried writing it like this:
hoverFunc($("div"), $(this).find("img"));
But obviously the "this" will not reference the first parameter. Is there a way to achieve this? Thanks
instead of this use event.target and pass event in mouseenter function call
mouseenter: function (event) {
$(event.target).find("img").hide(); //this being a reference to HoverElement
}
Use bind() to do this
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}.bind(HoverElement)
});
}
fnc.bind() Description
From your example,
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}
});
}
Here this withing mouseenter event is actually HoverElement's this. As you're binding the mouseenter on HoverElement, so withing event callback this is actually HoverElement.
DEMO

jQuery off() is not unbinding events when using bind

function bubble(content, triggerElm){
this.element = $('<div class="bubble" />').html(content);
this.element.css(.....) // here is positioned based on triggerElm
}
bubble.prototype.show = function(){
$(document).on('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype.hide = function(){
$(document).off('click', this._click.bind(this));
this.element.css(....)
};
bubble.prototype._click = function(event){
console.log('click', this);
if(this.element.is(event.target) || (this.element.has(event.target).length > 0))
return true;
this.hide();
};
var b = new bubble();
b.show();
b.hide();
I keep seeing click in the console, so the click does not unbind.
But if I remove the bind() call the click is unbinded. Does anyone know why? I need a way to be able to change "this" inside my test function, that's why I'm using bind().
The problem is that this._click.bind() creates a new function every time it's called. In order to detach a specific event handler, you need to pass in the original function that was used to create the event handler and that's not happening here, so the handler is not removed.
If there are only going to be a few bubbles in your app, you could and simply not use this. That will remove a lot of the confusion about what this is referring to and ensure that each bubble retains a reference to its own click function that can be used to remove the event as needed:
function bubble(content, triggerElm) {
var element = $('<div class="bubble" />').html(content);
element.css(.....); // here is positioned based on triggerElm
function click(event) {
console.log('click', element);
if (element.is(event.target) ||
element.has(event.target).length > 0) {
return true;
}
hide();
}
function show() {
$(document).on('click', click);
element.css(....);
}
function hide() {
$(document).off('click', click);
element.css(....);
}
return {
show: show,
hide: hide
};
}
var b1 = bubble(..., ...);
b1.show();
var b2 = bubble(..., ...);
b2.show();
See how this frees you from using contrivances like .bind() and underscore-prefixed methods.
One option would be to namespace the event:
$(document).on('click.name', test.bind(this));
$(document).off('click.name');
Example Here
try use jQuery's proxy to get a unique reference of your function.
In this way, when you call $.proxy(test, this), it will check if this function has already been referenced before. If yes, proxy will return you that reference, otherwise it will create one and return it to you. So that, you can always get your original function, rather than create it over and over again (like using bind).
Therefore, when you call off(), and pass it the reference of your test function, off() will remove your function from click event.
And also, your test function should be declared before use it.
var test = function(){
console.log('click');
};
$(document).on('click', $.proxy(test, this));
$(document).off('click', $.proxy(test, this));
http://jsfiddle.net/aw50yj7f/
Please read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
bind creates a new function therefore doing $(document).on('click', test.bind(this)); is like $(document).on('click', function(){}); and each time you execute it you invoke a new anonymous function thus you dont have a reference to unbind.
If you would do something like:
var test = function(){
console.log('click');
};
var newFunct = test.bind(this);
$(document).on('click', newFunct );
$(document).off('click', newFunct );
It should work fine
e.g: http://jsfiddle.net/508dr0hv/
Also - using bind is not recommended, its slow and not supported in some browsers.
rather than binding this to the event, send this as a parameter:
$("#DOM").on("click",{
'_this':this
},myFun);
myFun(e){
console.info(e.data._this);
$("#DOM").off("click",myFun);
}

Setting the 'this' context of an anonymous function within a JQuery Method

I want to pass a specific context the the following click bound method:
$(document).ready(function(){
var o = {
name : 'I\'m object O'
};
$('#my-button').click(function(){
alert(this.name);
}.call(o));
});
The problem is that this gets triggered as soon as the page loads. Is there a way I can bind a context to the anonymous function of the click handler and have it trigger only when the click event is fired? Also can you explain why its been triggered on the page load rather than the click event.
Use $.proxy
$("#my-button").click($.proxy(function () {
alert(this.name);
}, o));
It's not working because you are calling this anonymous function at the time of it's declaration. Try this instead:
$(document).ready(function(){
var o = {
name : 'I\'m object O'
};
$('#my-button').click(function(){
function(){
alert(this.name);
}.call(o)
});
/*
* Or shorter:
* $('#my-button').click(function(){
* alert(o.name);
* });
*/
});
$(document).mousedown(function(e){
//Do stuff
}

Javascript: How to pass an argument to a method being called without parentheses

Sorry for how stupid this is going to sound. My JS vocabulary is terrible and I had absolutely no idea what to search for.
I'm using jQuery.
So I've got this code:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){example.init();)
So here's the problem: I want to pass an argument to example.open() when I click the "a" element. It doesn't seem like I can, though. In order for the example.open method to just…exist on page-load and not just run, it can't have parentheses. I think. So there's no way to pass it an argument.
So I guess my question is…how do you pass an argument to a function that can't have parentheses?
Thanks so much.
Insert another anonymous function:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function()
{
example.open($(this));
});
}
};
You can also try this version because jQuery set the function's context (this) to the DOM element:
var example = {
open: function(){
alert($(this).text());
},
init: function(){
$("button").click(example.open);
}
};
Since jQuery binds the HTML element that raised the event into the this variable, you just have to pass it as a regular parameter:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function() {
// jQuery binds "this" to the element that initiated the event
example.open(this);
});
}
}
$(document).ready(function(){example.init();)
You can pass the anchor through its own handler:
var example = {
open: function( element ){
alert(element.text());
},
init: function(){
$("a").on("click", function() {
example.open( $(this) );
});
}
};
$(document).ready(function() {
example.init();
});
I don't understand what you actually want to do;
however, I can give a try:
var example = {
open: function(event){
event.preventDefault();
alert($(event.target).text()+' : '+event.data.x);
},
init: function(){
$("a").bind('click',{x:10},example.open);
}
};
$(example.init);
demo:
http://jsfiddle.net/rahen/EM2g9/2/
Sorry, I misunderstood the question.
There are several ways to handle this:
Wrap the call in a function:
$('a').click( function(){ example.open( $(this) ) } );
Where $(this) can be replaced by your argument list
Call a different event creator function, which takes the arguments as a parameter:
$('a').bind( 'click', {yourvariable:yourvalue}, example.open );
Where open takes a parameter called event and you can access your variable through the event.data (in the above it'd be event.data.yourvariable)
Errors and Other Info
However your element.text() won't just work unless element is a jQuery object. So you can jQueryify the object before passing it to the function, or after it's received by the function:
jQuery the passed object:
function(){ example.open(this) } /* to */ function(){ example.open($(this)) }
jQuery the received object:
alert(element.text()); /* to */ alert($(element).text());
That said, when calling an object without parameters this will refer to the object in scope (that generated the event). So, really, if you don't need to pass extra parameters you can get away with something like:
var example = {
open: function(){ // no argument needed
alert($(this).text()); // this points to element being clicked
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){
example.init();
}); // your ready function was missing closing brace '}'

Pass $(this) to a function

I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:
function showBox()
{
$(this).parents('.container').find('.box').show();
};
function hideBox()
{
$(this).parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
showBox();
},
function()
{
hideBox();
}
);
The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?
Per #patrickdw's answer, jQuery sets the scope of a callback for an event to the DOM element upon which the event was fired. For example, see the eventObject parameter in the documentation for the click() handler.
My original answer (below) is useful when you want to create a jQuery plug-in so that you may invoke your own custom methods on jQuery objects and have the jQuery object set as this during execution. However, it is not the correct and simple answer to the original question.
// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
function(){ $(this).showBox() },
function(){ $(this).hideBox() }
);
Edit: Or, if (as suggested) you want to add only one name to the ~global jQuery method namespace:
$.fn.myBox = function(cmd){
this.closest('.container').find('.box')[cmd]();
};
$('a').hover(
function(){ $(this).myBox('show') },
function(){ $(this).myBox('hide') }
);
Or more generally:
$.fn.myBox = function(cmd){
switch(cmd){
case 'foo':
...
break;
case 'bar':
...
break;
}
return this;
};
For more information, see the jQuery Plugin Authoring Guide.
The this will carry through if you just do:
$('a').hover(showBox,hideBox);
EDIT: To address the question in the comment, this will work for any function you assign as an event handler. Doesn't matter if it is an anonymous function or a named one.
This:
$('a').click(function() {
alert( this.tagName );
});
...is the same as:
function alertMe() {
alert( this.tagName );
}
$('a').click( alertMe );
...or this:
function alertMe() {
alert( this.tagName );
}
$('a').bind('click', alertMe );
In Javascript you can use call() or apply() to execute a function and explicitly specify this for it:
$('a').hover(
function()
{
showBox.call(this);
},
function()
{
hideBox.call(this);
}
);
The first parameter given to call() specifies the object that this will refer to in the function. Any further parameters are used as parameters in the function call.
You need to modify your code to something like this:
function showBox(elem)
{
elem.parents('.container').find('.box').show();
};
function hideBox(elem)
{
elem.parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
var $this = $(this);
showBox($this);
},
function()
{
var $this = $(this);
hideBox($this);
}
);
$('a').hover(function() {
$(this).closest('.container').find('.box').show();
}, function() {
$(this).closest('.container').find('.box').hide();
});
Add parameters to showBox and hideBox so that they can accept the element, and then call showBox($(this)) and hideBox($(this)).

Categories

Resources