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

Failed to ignore revisions in .git-blame-ignore-revs.

72 lines
1.7 KiB
JavaScript
Raw Normal View History

import { computed, get } from "@ember/object";
2018-06-15 23:03:24 +08:00
import extractValue from "./extract-value";
2015-08-12 05:34:02 +08:00
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 23:03:24 +08: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-12 05:34:02 +08:00
computedDescriptor = value;
} else {
computedDescriptor = callUserSuppliedGet(params, val);
}
} else {
2018-06-15 23:03:24 +08:00
throw new Error(
"ember-computed-decorators does not support using getters and setters"
);
2015-08-12 05:34:02 +08:00
}
return computed.apply(null, params.concat(computedDescriptor));
}
};
}
function niceAttr(attr) {
2018-06-15 23:03:24 +08:00
const parts = attr.split(".");
2015-08-12 05:34:02 +08:00
let i;
for (i = 0; i < parts.length; i++) {
2018-06-15 23:03:24 +08:00
if (
parts[i] === "@each" ||
parts[i] === "[]" ||
parts[i].indexOf("{") !== -1
) {
2015-08-12 05:34:02 +08:00
break;
}
}
2018-06-15 23:03:24 +08:00
return parts.slice(0, i).join(".");
2015-08-12 05:34:02 +08: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);
};
}