factory.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {
  2. forEach,
  3. bind
  4. } from 'min-dash';
  5. import Base from './base';
  6. /**
  7. * A model element factory.
  8. *
  9. * @param {Moddle} model
  10. * @param {Properties} properties
  11. */
  12. export default function Factory(model, properties) {
  13. this.model = model;
  14. this.properties = properties;
  15. }
  16. Factory.prototype.createType = function(descriptor) {
  17. var model = this.model;
  18. var props = this.properties,
  19. prototype = Object.create(Base.prototype);
  20. // initialize default values
  21. forEach(descriptor.properties, function(p) {
  22. if (!p.isMany && p.default !== undefined) {
  23. prototype[p.name] = p.default;
  24. }
  25. });
  26. props.defineModel(prototype, model);
  27. props.defineDescriptor(prototype, descriptor);
  28. var name = descriptor.ns.name;
  29. /**
  30. * The new type constructor
  31. */
  32. function ModdleElement(attrs) {
  33. props.define(this, '$type', { value: name, enumerable: true });
  34. props.define(this, '$attrs', { value: {} });
  35. props.define(this, '$parent', { writable: true });
  36. forEach(attrs, bind(function(val, key) {
  37. this.set(key, val);
  38. }, this));
  39. }
  40. ModdleElement.prototype = prototype;
  41. ModdleElement.hasType = prototype.$instanceOf = this.model.hasType;
  42. // static links
  43. props.defineModel(ModdleElement, model);
  44. props.defineDescriptor(ModdleElement, descriptor);
  45. return ModdleElement;
  46. };