Hi,
After diving into the micro-library,aka Backburner, that powers the Ember Run loop I decided to write a blogpost about it so that developers can have an idea of what it actually doing.
First of all you can find the source code for Ember.run here => ember.js/packages/ember-metal/run_loop.js.
Ember defines some callback functions before creating an instance of Backburner, such as:
onBegin => defines a currentRunLoop in the current instance of the backburner object and sets its to the currentInstance.
Backburner calls this callback whenever you create a new instance. This callback takes two arguments (currentInstance, previousInstance).
onEnd => Ember now sets the currentRunLoop to be the next instance which is returned by Backburner which is the last instance in the instanceStack that BackBurner keeps. This callback also takes two arguments (currentInstance, nextInstance).
It also sets the default Backburner queue to be the “actions” queue and the onErrorTarget to Ember itself and the onErrorMethod to “onerror” which is defined in Ember itself so when Backburner tries to flush it will check whether or not it should invoke, call the method passed in passing its target and arguments, with one error or not. It uses invokeWithOnError if an error occurs it will call the ‘onerror’ method defined before in the onErrorTarget which in this case is Ember itself.
You can see this snippet here: https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/run_loop.js#L22-L33
Great now we have an instance of the Backburner object ready to be used, let imagine the following scenario:
setNameOnPage: function(name) { this.$('name').val(name); }, updateName: function() { setNameOnPage("Antonio"); setNameOnPage("EmberRocks"); setNameOnPage("Yehuda"); }, changeName: function() { Ember.run(function() { Ember.run.once(this.updateName); }); }.observe('name')
So every time “name” changes ember will run the changeName property which creates/joins a run loop and tells the run loop, backburner, to run the “updateName” function once. Ember.run.once sets the default queue to be the “actions” queue and call the backburner scheduleOnce method, which is an alias to deferOnce in the Backburner object. Every time you or ember calls “run.once” the only thing that backburner will change is the arguments and the stack which is an instance of the Error object if debug is true.
Ember Run loop uses a GUID(i.e Global Unique Identifier) which I will cover in another blogpost, as I do not fully understand what it does yet.
As you can see here: https://github.com/ebryn/backburner.js/blob/master/lib/backburner/queue.js#L43-L100
I hope this post gives you an idea on what the Ember Run Loop is doing, Please leave your feedback/corrections bellow.