ranking Sort Sort   |   date Sort Sort   |   member Sort Sort

Date Submitted Thu. Dec. 20th, 2007 6:48 PM
Revision 1
Scripter Fordiman
Tags JavaScript | promise | Prototype
Comments 1 comments
This is a version of my previous entrant, Promise, that will work with prototype, but does not require it. It's slightly more advanced, using .apply here and there.

It's basically a function to allow any other function to poll. Polling is generally regarded as bad practice in object oriented code, but can make very simple the matter of, for example, running a bit of code only after a single-run event (like onload) occurs (whether that be in the future or past), another unrelated bit of code needs to be hack-tracked, or any other generic condition.

Note that when the function runs, it doesn't necessarily run within the scope that's called it. Its context is set to itself, rather than its normal context, and it's asynchronous, so you'll not get a return value. If you use Prototype, you can bind the function and it'll behave as it should in terms of context, but I'm unaware of a way to cause an asynch function to block execution - and you'd really rather that not happen anyway, trust me.
Date Submitted Fri. Sep. 28th, 2007 2:08 AM
Revision 1
Scripter Fordiman
Tags JavaScript | promise | Prototype
Comments 6 comments
Here's a quick lil' addon for Prototype that I use often.

Prototype.Promise(condition, action, interval)
condition is a string that you want met before an action is run.
action is a function that does the action.
interval is the polling rate for condition in seconds, and defaults to 1

So, for example, you may want function foo to run, but only once bar has been set:

function foo(a,b) {
var thingy = {

Then, in some point in the mysterious future, thingy.retVal gets set to 5, at which point, the Promise goes into effect, and thingy.retVal becomes 10.

Where I find this particularly useful is in making sure that a document is loaded before doing something (condition="$$('body').length>=1), as you can see it used for the include functions.

Speaking of which, the following include functions are great for getting scripts and stylesheets into your page. I won't bother with examples, as they're pretty straightforward.

Meanwhile, Prototype.scriptPath will point to wherever in your server's heirarchy Prototype was loaded from. The regex, you'll note allows for names like prototype.compressed.js, prototype.modified.js, 2007-09-28.prototype.js, etc - just in case you want to keep track of your various hacks of Prototype, as I do.