I am creating a Javascript object that contains a function that executes a jQuery each
method like the following:
function MyClass {
Method1 = function(obj) {
// Does something here
}
Method2 = function() {
$(".SomeClass").each(function() {
// 1 2
this.Method1(this);
});
}
}
Which object is each THIS
referring to? jQuery is referring to the item returned from the each
iteration. However, I would like This[1]
to refer to the containing class...
How can I refer to the containing class from within the jQuery loop?
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
Difference between this and $(this)The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.
I guess you could do something like this:
function MyClass {
Method1 = function(obj) {
//do something here
}
Method2 = function () {
var containingClass = this;
$(".SomeClass").each(function () {
containingClass.Method1(this);
});
}
}
}
From http://docs.jquery.com/Core/each:
This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element. Note that 'this' does not point to a jQuery object.
Personally, I prefer using explicit parameters. This way, it is more easily readable:
$('#rotfl').each(function(index, domObject)
{
var jQueryObject = $(domObject);
// code
});
To answer your question: JavaScript has dynamic static scope. You can do the following:
var that = this;
$('#rotfl').each(function(index, domObject)
{
var jQueryObject = $(domObject);
that.DoSomething();
// code
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With