PDA

View Full Version : dynamic function argument within an object


fci
05-04-2005, 03:38 PM
i'm not sure if the title of the thread is a good description. meh.

<script type="text/javascript">
function my_object() {
var self = this;
this.my_method = function() {
for (var i=0; i<10; i++) {
setTimeout(function() { self.blah(i); }, 1000);
}
};
this.blah = function(i) {
document.getElementById('yeah').innerHTML += i + '<br/>';
};
}
window.onload = function() {
var obj = new my_object();
obj.my_method();
}
</script>

<div id="yeah"></div>


the desired output would be 0...9
i have setup something else for now which works in my current case.. but I've wanted to do something like the above before but I couldn't figure it out..


ahh! just figured it out while giving it my last shot.

function my_object() {
var self = this;
this.my_method = function() {
var x;
var test;
for (var i=0; i<10; i++) {
test = function() {
var x = i;
setTimeout(function() { self.blah(x); }, 100);
}
test();
}
};
this.blah = function(j) {
document.getElementById('yeah').innerHTML += j + '<br/>';
};
}
window.onload = function() {
var obj = new my_object();
obj.my_method();
}
</script>

<div id="yeah"></div>


thanks for looking at the thread .. i guess... feel free to post comments then..

Kor
05-04-2005, 05:01 PM
feel free to post comments then..

For the moment it looks unecessary intricate to me. It looks even close to a closure to me... Why so many self references? What is your intention, after all?

fci
05-04-2005, 06:30 PM
non-working example but may fill in some of the blanks since it is more in context...
<script type="text/javascript">
function Alarm_clock() {
var self = this;

this.load_alarms = function() {
/* fetch xml with ajax */
response = response.responseXML.getElementsByTagName('appt');

var timeout;

for (var i=0; i<response.length; i++) {

timeout = function() {
var x = i;
setTimeout(function() { Alarm_clock.alert( { id: response[x].getAttribute('id'), text: response[x].innerHTML } ); }, 100); // the 100 would typically be variable
}
timeout();
}
};

}

Alarm_clock.alert = function(alarm) {
document.getElementById('yeah').innerHTML += 'ding ding ding, alarm' + alarm.id + ' ' + alarm.text + '<br/>'; // this will possibly be more elaborate then this..
};

window.onload = function() {
var obj = new Alarm_clock();
obj.load_alarms();
}
</script>

<div id="yeah"></div>

does that help? .... i just needed the i to be passed properly without being changed for doing the setTimeout