Skip to content

Instantly share code, notes, and snippets.

@joeytrapp
Last active October 14, 2015 01:28
Show Gist options
  • Save joeytrapp/4286733 to your computer and use it in GitHub Desktop.
Save joeytrapp/4286733 to your computer and use it in GitHub Desktop.
Ember.js utility to generate a controller computed property that compares a string to a part of the currentPath. Used to create boolean properties that update on based on the state of the application.
Ember.PathCompare = {
comparePartsToString: function(parts, compare, index) {
var str, first;
if (index === undefined) {
index = parts.length - 1;
} else {
if (index < 0) {
index = (parts.length - 1) - (index * -1);
}
}
str = parts[index];
first = compare[0];
if (first === '!') {
return str !== compare.slice(1);
} else {
return str === compare;
}
},
comparePartsToArray: function(parts, arr) {
var str, first, index, compare = arr[0];
if (arr[1] !== undefined) {
index = arr[1];
if (index < 0) {
index = (parts.length - 1) - (index * -1);
}
} else {
index = parts.length - 1;
}
str = parts[index];
first = compare[0];
if (first === '!') {
return str !== compare.slice(1);
} else {
return str === compare;
}
},
compare: function(parts, options) {
var self = this, val = false;
if (!parts) return val;
if (typeof options === 'string') {
val = self.comparePartsToString(parts, options);
}
if ($.isArray(options)) {
if ($.isArray(options[0])) {
val = true;
options.forEach(function(i) {
if ($.isArray(i)) {
val = val && self.comparePartsToArray(parts, i);
}
if (typeof i === 'string') {
val = val && self.comparePartsToString(parts, i);
}
});
} else {
val = self.comparePartsToArray(parts, options);
}
}
return val;
},
create: function(options) {
var self = this, compare = self.compare;
return function() {
var bits = this.get('target.router.currentHandlerInfos').reduce(function(memo, item) {
memo.push(item.name);
return memo;
}, []);
return compare.call(self, bits, options);
}.property('application.currentPath');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment