Skip to content

Instantly share code, notes, and snippets.

@chrisjlee
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisjlee/31d1ea4f7cd90517b2d8 to your computer and use it in GitHub Desktop.
Save chrisjlee/31d1ea4f7cd90517b2d8 to your computer and use it in GitHub Desktop.
EmberJS - random collection. Stolen from: https://coderwall.com/p/jmcxqg
Ember.SortedArrayController = Ember.ArrayController.extend({
sortOrder: "normal",
sortFunction: null,
inputCollectionName: "content",
outputCollectionName: "content",
maxCollectionSize: -1,
init: function() {
this.set(this.inputCollectionName, []);
this.addObserver(this.inputCollectionName + '.@each', function() {
return this.elementAdded();
});
return this.addObserver(this.outputCollectionName + '.@each', function() {
return this.trimArray();
});
},
elementAdded: (function() {
var content, context;
context = this;
content = this.get(this.inputCollectionName);
if (this.sortOrder === "normal") {
if (this.sortFunction != null) {
content.sort(function(a, b) {
return context.sortFunction(a, b);
});
} else {
content.sort();
}
} else if (this.sortOrder === "reverse") {
if (this.sortFunction != null) {
content.sort(function(a, b) {
return context.sortFunction(b, a);
});
} else {
content.reverse();
}
} else if (this.sortOrder === "random") {
content.sort(function(a, b) {
return 0.5 - Math.random("deadbeef");
});
}
return this.set(this.outputCollectionName, content);
}),
trimArray: (function() {
var content;
content = this.get(this.outputCollectionName);
if ((this.maxCollectionSize > 0) && (content.length > this.maxCollectionSize)) {
return this.set(this.outputCollectionName, content.slice(0, this.maxCollectionSize - 1));
}
})
});
window.myArray = Ember.SortedArrayController.create();
myArray.content.pushObjects(["Jack", "Cassandra", "Raj"]);
window.myArray2 = Ember.SortedArrayController.create({
sortOrder: "reverse"
});
myArray2.content.pushObjects(["Jack", "Cassandra", "Raj"]);
window.myArray3 = Ember.SortedArrayController.create({
sortOrder: "random"
});
myArray3.content.pushObjects(["Jack", "Cassandra", "Raj"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment