So I've been searching on this because it's giving me a headache not being able to achieve this... And seems like there is no solution the way I expected to be.
Let's assume we have a sample PHP class:
<?php
class SampleClass {
function doA() {
echo 'Hello world';
}
function doB() {
$sampleArray = ['Hey', 'You'];
foreach( $sampleArray as $key => $value ) {
self::doA();
}
}
}
?>
This code will echo Hello World two times because of the foreach loop. And thats good.
Now I have this script:
function SectionHandler($appWrap) {
this.appWrap = $appWrap;
this.loading = function() {
this.appWrap.addClass('section-loading').html("<i class='fa fa-refresh fa-2x fa-spin'></i>");
}
this.setError = function($info) {
this.appWrap.addClass('section-error').html($info);
}
this.load = function($section) {
var $fileCheck = $.get($section).success(function(){
self.loading();
self.load($section);
}).fail(function(){
self.setError('No se pudo cargar los datos especificados desde ' + $section + ' ;');
});
}
}
I believe that this.loading() is no longer pointing to the main function because of the $.get().success() function. I do not know the real reason.
The problem is that none of this.loading(), this.load(), this.setError() is working.
So, how I do to point to the main function like I were using PHP self:: function.?
As @Eclecticist pointed out the line this.load($section); will execute untill it fails or gets an error, I change the whole check to this:
var $fileCheck = $.get($section).done(function(response){
self.appWrap.html(response);
}).fail(function(){
self.setError('No se pudo cargar los datos especificados desde ' + $section);
});
Try this:
function SectionHandler($appWrap) {
var that = this;
this.appWrap = $appWrap;
this.loading = function() {
that.appWrap.addClass('section-loading').html("<i class='fa fa-refresh fa-2x fa-spin'></i>");
}
this.setError = function($info) {
that.appWrap.addClass('section-error').html($info);
}
this.load = function($section) {
var $fileCheck = $.get($section).success(function(){
that.loading();
that.load($section);
}).fail(function(){
that.setError('No se pudo cargar los datos especificados desde /[ ' + $section + ' ]\ ;');
});
}
}
The problem is the value of this changes once you're inside of a function. You can address it by declaring a variable within your main function, that, and reference it later on.
--edit--
I want to note that the line that.load($section); will recursively call SectionHandler.load() until the AJAX request either fails, or until you get a stackoverflow error.
And yes, I've been hoping something came up where I could reference that error :)
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