2

i've a problem... What am I doing wrong?

I want to use a selector previously saved in a variable. The idea is to use it within a function in an object.

var escribir = {
    obj:$('#cont'),
    algo: function(i) { 
        escribir.obj.html(i++);
        setTimeout('escribir.algo('+i+')',1000);
    }
}

$(document).ready(
    function(){
    escribir.algo(0);
    }
);

....
<div id="cont"></div>
1
  • the problem is... obj:$('#cont') and escribir.obj.html(i++); not work... Commented Apr 19, 2012 at 7:36

3 Answers 3

1
var escribir = {
    obj : $('#cont'),
    algo : function (i) {
           |
           V
        escribir.obj.html(i++);
        setTimeout(function() { escribir.algo(i) }, 1000); // Don't use `eval`
    }
}

EDIT: Working example here http://jsfiddle.net/elclanrs/sQdST/

Sign up to request clarification or add additional context in comments.

1 Comment

Passing in a function call to setTimeout won't work. If not the eval version (which is, yeah, evil) you'll have to pass in a function reference. So you'll have to wrap that in a lambda : setTimeout(function () { escribir.algo(i); }, 1000);.
0

You'd probably be better if you made use of closures in better form.

jQuery(function ($) {

    var escribir = {
        obj : $('#cont'),
        algo_counter : 0,
        algo : function () {
            escribir.obj.html(escribir.algo_counter++);
            setTimeout(escribir.algo, 1000);
        }
    };

    // optionally:
    // escribir.algo_counter = 10;

    escribir.algo();

}

This way, you're not using setTimeout's eval version.

Comments

0

Your obj is the member of escribir, so you need to change it to escribir.obj:

var escribir = {
    obj:$('#cont'),
    algo: function(i) { 
        escribir.obj.html(i++); // without escribir.obj you will get reference error, otherwise you have a variable name obj.
        setTimeout('escribir.algo('+i+')',1000);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.