Skip to content

Instantly share code, notes, and snippets.

@endash
Last active August 29, 2015 14:08
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 endash/a8bfddce4caaf6524133 to your computer and use it in GitHub Desktop.
Save endash/a8bfddce4caaf6524133 to your computer and use it in GitHub Desktop.
Ember.autoComputed = function () {
var args = Array.prototype.slice(arguments);
if (!args.length) return;
var func = args.pop();
if (typeof func !== 'function') return;
var depKeys = args.slice(0, -1);
if (!depKeys.length) return Ember.computed(func);
var str = func.toString();
var funcDef = str.substr(0, str.indexOf('{'}));
var openParIndex = funcDef.indexOf('(');
var closeParIndex = funcDef.indexOf(')');
var funcArgs = funcDef.substr(openParIndex + 1, closeParIndex - openParIndex - 1);
var newArgs = funcArgs.length ? funcArgs.split(", ") : [];
var funcBodyStartIdx = str.indexOf('{');
var funcBodyEndIdx = str.lastIndexOf('}');
var funcBody = str.substr(funcBodyStartIdx + 1, funcBodyEndIdx - funcBodyStartIdx - 1);
var newFunc = [];
for (var i = 0, depKey; i < depKeys.length; i++) {
depKey = depKeys[i];
newFunc.push("var " + depKey + " = this.get('" + depKey + "');"));
}
newFunc.push(funcBody);
newFunc = newFunc.join("\n");
newArgs.push(newFunc);
var computedProps = depKeys.concat([Function.apply(null, newArgs)])
return Ember.computed.apply(null, computedProps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment