This repository has been archived on 2023-03-18. You can view files and clone it, but cannot push or open issues or pull requests.
osr-discourse-src/app/assets/javascripts/discourse/mixins/singleton.js
2013-08-08 13:00:48 -04:00

106 lines
2.3 KiB
JavaScript

/**
This mixin allows a class to return a singleton, as well as a method to quickly
read/write attributes on the singleton.
Example usage:
```javascript
// Define your class and apply the Mixin
User = Ember.Object.extend({});
User.reopenClass(Discourse.Singleton);
// Retrieve the current instance:
var instance = User.current();
```
Commonly you want to read or write a property on the singleton. There's a
helper method which is a little nicer than `.current().get()`:
```javascript
// Sets the age to 34
User.currentProp('age', 34);
console.log(User.currentProp('age')); // 34
```
If you want to customize how the singleton is created, redefine the `createCurrent`
method:
```javascript
// Define your class and apply the Mixin
Foot = Ember.Object.extend({});
Foot.reopenClass(Discourse.Singleton, {
createCurrent: function() {
return Foot.create({toes: 5});
}
});
console.log(Foot.currentProp('toes')); // 5
```
@class Discourse.Singleton
@extends Ember.Mixin
@namespace Discourse
@module Discourse
**/
Discourse.Singleton = Em.Mixin.create({
/**
Returns the current singleton instance of the class.
@method current
@returns {Ember.Object} the instance of the singleton
**/
current: function() {
if (!this._current) {
this._current = this.createCurrent();
}
return this._current;
},
/**
How the singleton instance is created. This can be overridden
with logic for creating (or even returning null) your instance.
By default it just calls `create` with an empty object.
@method createCurrent
@returns {Ember.Object} the instance that will be your singleton
**/
createCurrent: function() {
return this.create({});
},
/**
Returns or sets a property on the singleton instance.
@method currentProp
@param {String} property the property we want to get or set
@param {String} value the optional value to set the property to
@returns the value of the property
**/
currentProp: function(property, value) {
var instance = this.current();
if (!instance) { return; }
if (typeof(value) !== "undefined") {
instance.set(property, value);
return value;
} else {
return instance.get(property);
}
}
});