开发者

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?


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();
});


Try this code:

$(document).ready(function(){
    var refreshTimeout,
        rms = new RMS();

    rms.refresh();

    function RMS() {
        this.refresh = function(){
            $.post(refreshUrl, {ids: $('#ids').val()}, function(response){
                if (typeof(response) != 'undefined') {
                    $('#rms').attr('value', response.rms);
                }
                refreshTimeout = setTimeout(function() { rms.refresh(); }, 2000);
            }, 'json');
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜