How to access attribute in jQuery callback func? - javascript

var some_name =
{
moving:false,
show : function ()
{
this.moving = true;
$('element').slideDown(5000, function ()
{
this.moving = false; //How to access to attribute "moving" of class some_name?
});
},
}
Question in code.

You can bind the callback function to the current context:
$('element').slideDown(5000, $.proxy(function() {
this.moving = false;
}), this); // "this" inside of the function will be this "this"
See jQuery.proxy
Alternatively you could do this:
this is the current context, it's value depends on how the function is called. You can assign this to a variable outside of the function, and use this variable instead:
var that = this;
$('element').slideDown(5000, function() {
that.moving = false; //use that instead of this here
});

Use moving instead of this.moving (in both occurences)
Variables are bound to the context when they are used, so even inside your event callback you can access the variables above.

In the event callbacks, this refers to event.target, or the element that captured the event.
You can take the advantage of closures in javascript and access the moving attribute like this:
show : function ()
{
var moving = true;
$('element').slideDown(5000, function ()
{
moving = false;
});
},
Note, though, that this moving will be different of the first moving that lives in some_name

Related

Jquery this returns empty object when calling from another function

i have a normal function which works and when i console log this it returns jQuery.fn.init [small.expand, context: small.expand
My function below:
jQuery(document).on('click', 'h3.shipping-name small.expand', function (e) {
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
});
But if i want to get it from another function like this:
var smallExpand = jQuery('h3.shipping-name small.expand');
smallExpand.on("click", function () {
expandDetails();
});
function expandDetails(e) {
alert("oki2");
var me = jQuery(this);
console.log(me);
var next = me.parent().next().next();
console.log(next)
if (next.is(":hidden")) {
me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
} else {
me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
next.slideToggle();
}
But it returns only empy object like this: jQuery.fn.init {}
What am i doing wrong?
Problem with your implementation is that this doesn't refers to current element it refers to window object thus the code doesn't work
You can use call() to set the this value
smallExpand.on("click", function (event) {
expandDetails.call(this, event);
});
Or, You could just pass the function reference to attach event handler
smallExpand.on("click", expandDetails);
Set the variable first out side your functions, then you can retrieve it for later.
var me;
Then
function first() {
me = $(this);
}
Now you can use the variable in another function
function thisorthat() {
$(‘.class’).val(me);
}
You are calling expandDetails as a static method.
as mentioned by #Satpal, you should just do smallExpand.on("click", expandDetails);.
this exists in the smallExpand.on("click", function() {}); scope, but once you call expandDetails(); it gets lost.

Using onclick() inside another function

function layoutMod() {
standardId = document.getElementById("standard");
fancyId = document.getElementById("fancy");
standardId.onclick = function() {
standard();
};
fancyId.onclick = function() {
fancy();
};
};
How can I use the onclick events defined above in a function??? Is it a good practice to load the function at page load?? I need to define in a function the onclick event beacuse I don't want to use global variables.
What you've written should work. However, you should note that by not using the var keyword, you're still creating global variables inside of your function. I would suggest...
function onloadHandler() {
document.getElementById("standard").onclick = function() {
// Do something
};
document.getElementById("fancy").onclick = function() {
// Do something else
};
};
It can get messing when you nest functions inside of each other. In this case, I would suggest removing the outer function so that your code looks like this:
document.getElementById("standard").onclick = function() {
standard();
};
document.getElementById("fancy").onclick = function() {
fancy();
};
The code does not need to be in a function, it will automatically be run on page load. Since you don't want global variables, just don't use variables at all.

What this JavaScript function method called?

I am quite interested when I run this simple function
$(window).resize(function() {
var that = $(this);
var widthValue = that.width();
console.log(widthValue + 'px');
});
It works when I start resizing my browser window.
But when I do this
$(window).resize(function() {
var that = $(this);
var widthValue = that.width();
console.log(widthValue + 'px');
}).resize();
It acts like load();. I added resize() at the end.
What is this called? Not sure I understand why and how this works.
The technique is called Chaining.
It boils down to a function returning this at the end, so you can call another method of the same object by chaining the method calls one after the other.
var foo = {
count: 0,
up: function () { this.count++; return this; },
show: function () { alert(this.count); return this; }
}
foo.show().up().show().up().up().show();
In this particular example, the resize method is overloaded. If you give it a function argument then it will bind that function as an event handler. If you call it without arguments, then it will trigger that event instead.
With the 2nd case, you are invoking or triggering the resize event.

Acces member variables in nested functions

I have a class which uses jQuery functions inside it's internal function.
How can I refer to the member variable inside the jQuery callback function?
See the code below:
var UriParser = function(uri) {
this._uri = uri; // let's say its http://example.com
};
UriParser.prototype.testAction = function() {
$('a').on('click', function(event) {
// I need the above this._uri here,
// i.e. http://example.com
}
}
The problem is this inside the event handler does not refer the UriParser object, it is referring the dom element which was clicked.
One solution is to use a closure variable
UriParser.prototype.testAction = function () {
var self = this;
$('a').on('click', function (event) {
//use self._uri
})
}
another is to use $.proxy() to pass a custom execution context
UriParser.prototype.testAction = function () {
$('a').on('click', $.proxy(function (event) {
//use this._uri
}, this))
}

Passing Parameters into a Callback Function

I have a function that listens for a click on the screen and fires a callback. It is part of a Helper object (which is why is preceded by the term Helper in my sample code. That is irrelevant however.
var Helper = {
bodyClickListener: function(fn) {
var window = document.getElementsByTagName('body')[0];
window.click();
CORE.dom.on(window, 'click', function(event) {
CORE.dom.off(window, 'click');
fn(event);
});
}
}
I need to be able to pass a function into this function with a parameter that has been previously set.
function someFunction() {
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
function removePopup(element) {
if(element) {
element.parentNode.removeChild(element);
}
};
}
The code above works, but you'll notice that I have to set the popup variable inside of the callback function. It has already been set above. How do I pass a reference to the earlier variable into the callback function.
If I understand your question correctly, you don't need to do much. You can just use the popup variable defined outside.
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(event) {
event.stopPropagation();
//Don't set it
//var popup = document.getElementById('tagResultsPopup');
removePopup(popup);//popup will refer to the correct variable
});
The function that you are passing to bodyClickListener is a closure. You can simply reference 'popup' inside that function without any problem. You don't have to create a new variable.
The answer was to use closure in this way:
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
That way the callback function has access to the variable I pass into the parameter function. So here, the return is actually the function I am passing as the callback.

Categories