Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with jquery inside OOP function

Hello I'm trying to get value of hidden element in my OOP function. Here is code:

var refreshTimeout;
var rms = new RMS();
rms.refresh();

function RMS() {
    this.refresh = function(){
        alert($("#ids").val());
        $.post(refreshUrl, {ids: $("#ids").val()}, function(response){
            var result = $.parseJSON(response);

            if (result != null) {
                $("#rms").attr("value", result.rms);
            }

            refreshTimeout = setTimeout(function() { rms.refresh(); }, 2000);
        });
    }
}

The problem is that $("#ids").val() works in firebug console but not inside rms.refresh()...

What I'm doing wrong?

like image 305
Mirgorod Avatar asked Feb 15 '26 00:02

Mirgorod


1 Answers

Your invocation of $('#ids').val() looks fine, so long as the DOM is loaded at this point (i.e. inside a $(document).ready() block).

Your timer function looks a little suspect, though. You're referring to rms which is in the outer scope, when you should be referring to whatever the current object is.

Similarly your timer-related values should be properly encapsulated inside the class, since otherwise you can't have more than one instance.

// class definition - can be loaded anywhere
var RMS = function(ids, rms) {

    var self = this;
    var timer = null;
    var delay = 2000;

    this.refresh = function() {
        $.post(refreshUrl, {ids: $(ids).val()},
            function(response) {
                var result = $.parseJSON(response);
                if (result != null) {
                    $(rms).attr("value", result.rms);
                }

                timer = setTimeout(function() {
                    self.refresh();
                }, delay);
            }
        );
    };
};

// invocation deferred until the DOM is ready
$(document).ready(function() {
   var rms = new RMS('#ids', '#rms');
   rms.refresh();
});
like image 176
Alnitak Avatar answered Feb 17 '26 13:02

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!