Created
May 1, 2013 17:09
-
-
Save eykd/5496647 to your computer and use it in GitHub Desktop.
A lock implementation using a Backbone Model and jQuery Deferred. Only one caller can "own" the lock at a time. The lock maintains an internal queue of Deferreds that it resolves, in order, as it is released.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var Lock = Backbone.Model.extend({ | |
| initialize: function () { | |
| this._queue = []; | |
| this.set('_locked', false); | |
| this.on('change:_locked', this._on_change_lock, this); | |
| }, | |
| _on_change_lock: function (m, locked) { | |
| if (!locked && this._queue.length) { | |
| var d = this._queue.shift(); | |
| this._lock(); | |
| d.resolve(this); | |
| } | |
| }, | |
| _lock: function () { | |
| if (!this.get('_locked')) { | |
| this.set('_locked', true); | |
| console.log("Locked."); | |
| } | |
| }, | |
| _unlock: function () { | |
| if (this.get('_locked')) { | |
| this.set('_locked', false); | |
| console.log("Unlocked."); | |
| } | |
| }, | |
| acquire: function () { | |
| var d = new $.Deferred(); | |
| if (this.get('_locked')) { | |
| this._queue.push(d); | |
| } else { | |
| d.resolve(); | |
| this._lock(); | |
| } | |
| return d.promise(); | |
| }, | |
| release: function () { | |
| this._unlock(); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment