Javascript Callback when variable is set to X
Have an issue I can't seem to wrap my head around. I'm wanting to write a generic javascript function that will accept a variable and a callback, and continue to execute until that variable is something other than false.
For example, the variable SpeedFeed.user.sid is false until something else happens in the code, but I don't want to execute a particular callback until it has been set.
The call:
SpeedFeed.helper_ready(SpeedFeed.user.sid, function(){
alert(SpeedFeed.user.sid);
// Run function that requires sid to be set.
});
The function:
helper_ready: function(vtrue, callback){
if(vtrue != false){
callback();
} else {
setTimeout(function(){
SpeedFeed.helper_ready(vtrue, callback);
}, SpeedFeed.apiCheckTime);
}
}
The iss开发者_如何学Goue I've narrowed it down to appears to be that because in the setTimeout I call vtrue instead of the actual SpeedFeed.user.sid, it's going to be set to false always. I realize I could write a specific function for each time that just evaluates the SpeedFeed.user.sid, but I'd like to have a generic method that I could use throughout the application.
Thanks for any insight :)
You are passing in the current value of vtrue
to setTimeout
which then repeats the process so the parameter vtrue
is always the same (vtrue
is immutable).
Instead of writing a callback-like function that checks whenever a particular value is true, why not make setter and getter functions that can invoke callback()
or just call callback()
directly whenever vtrue
would be true
? The code will be much easier to follow this way and you will not need hacks such as setTimeout
looping.
There are multiple solutions to this problem that do not require a callback. One conventional approach would be to use setters and getters instead of assignments.
In addition to @Trey answer, since I was also thinking of setter
and getter
. In addition to set and get functionality I would suggest to add something like registerListener
and unregisterListener
which will register listeners to follow the state of your variable. And then each time getter is called iterate over all listeners and tell them about updated value, or just pass this value to them.
Pass to helper_ready three parameters: source_object, object`s_property, callback
and then check status of object`s property. in your case it will be
SpeedFeed.helper_ready(SpeedFeed.user, "sid", function(){
alert(SpeedFeed.user.sid);
// Run function that requires sid to be set.
});
for global property:
SpeedFeed.helper_ready(window, "sid", function(){
alert(windwo.sid);
// Run function that requires sid to be set.
});
Instead of timeout use setInterval
. See this question. It is similar to what you're trying to do.
精彩评论