1
0
Fork 0
freesewing/src/attributes.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

function Attributes(init = false) {
2018-07-23 20:14:32 +02:00
this.list = {};
if (init) {
for (let key in init) {
let val = init[key];
this.add(key, val);
}
}
2018-07-23 20:14:32 +02:00
}
2018-07-23 20:14:32 +02:00
/** Adds an attribute */
Attributes.prototype.add = function(name, value) {
2018-07-23 20:14:32 +02:00
if (typeof this.list[name] === "undefined") {
this.list[name] = [];
}
this.list[name].push(value);
2018-07-14 16:04:39 +00:00
2018-07-23 20:14:32 +02:00
return this;
};
/** Sets an attribute, overwriting existing value */
Attributes.prototype.set = function(name, value) {
this.list[name] = [value];
return this;
};
2018-07-23 20:14:32 +02:00
/** Retrieves an attribute */
Attributes.prototype.get = function(name) {
2018-07-23 20:14:32 +02:00
if (typeof this.list[name] === "undefined") return false;
else return this.list[name].join(" ");
};
/** Returns SVG code for attributes */
Attributes.prototype.render = function() {
2018-07-23 20:14:32 +02:00
let svg = "";
for (let key in this.list) {
svg += ` ${key}="${this.list[key].join(" ")}"`;
}
2018-07-23 20:14:32 +02:00
return svg;
};
/** Returns SVG code for attributes with a fiven prefix
* typically used for data-text*/
Attributes.prototype.renderIfPrefixIs = function(prefix = "") {
2018-07-23 20:14:32 +02:00
let svg = "";
let prefixLen = prefix.length;
for (let key in this.list) {
if (key.substr(0, prefixLen) === prefix) {
svg += ` ${key.substr(prefixLen)}="${this.list[key].join(" ")}"`;
}
}
2018-07-23 20:14:32 +02:00
return svg;
};
2018-07-23 11:12:06 +00:00
2018-08-03 14:20:28 +02:00
/** Returns a deep copy of this */
Attributes.prototype.clone = function() {
let clone = new Attributes();
2018-08-03 14:20:28 +02:00
clone.list = JSON.parse(JSON.stringify(this.list));
return clone;
};
export default Attributes;