discourse/app/assets/javascripts/ember-addons/utils/handle-descriptor.js.es6

74 lines
1.7 KiB
Plaintext
Raw Normal View History

2018-06-15 11:03:24 -04:00
import Ember from "ember";
import extractValue from "./extract-value";
2015-08-11 17:34:02 -04:00
const { computed, get } = Ember;
export default function handleDescriptor(target, key, desc, params = []) {
return {
enumerable: desc.enumerable,
configurable: desc.configurable,
writeable: desc.writeable,
initializer: function() {
let computedDescriptor;
if (desc.writable) {
var val = extractValue(desc);
2018-06-15 11:03:24 -04:00
if (typeof val === "object") {
let value = {};
if (val.get) {
value.get = callUserSuppliedGet(params, val.get);
}
if (val.set) {
value.set = callUserSuppliedSet(params, val.set);
}
2015-08-11 17:34:02 -04:00
computedDescriptor = value;
} else {
computedDescriptor = callUserSuppliedGet(params, val);
}
} else {
2018-06-15 11:03:24 -04:00
throw new Error(
"ember-computed-decorators does not support using getters and setters"
);
2015-08-11 17:34:02 -04:00
}
return computed.apply(null, params.concat(computedDescriptor));
}
};
}
function niceAttr(attr) {
2018-06-15 11:03:24 -04:00
const parts = attr.split(".");
2015-08-11 17:34:02 -04:00
let i;
for (i = 0; i < parts.length; i++) {
2018-06-15 11:03:24 -04:00
if (
parts[i] === "@each" ||
parts[i] === "[]" ||
parts[i].indexOf("{") !== -1
) {
2015-08-11 17:34:02 -04:00
break;
}
}
2018-06-15 11:03:24 -04:00
return parts.slice(0, i).join(".");
2015-08-11 17:34:02 -04:00
}
function callUserSuppliedGet(params, func) {
params = params.map(niceAttr);
return function() {
let paramValues = params.map(p => get(this, p));
return func.apply(this, paramValues);
};
}
function callUserSuppliedSet(params, func) {
params = params.map(niceAttr);
return function(key, value) {
let paramValues = params.map(p => get(this, p));
paramValues.unshift(value);
return func.apply(this, paramValues);
};
}