SvgPathBindingHandler.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const svgNS = "http://www.w3.org/2000/svg";
  2. const svgClassName = "cesium-svgPath-svg";
  3. /**
  4. * A Knockout binding handler that creates a DOM element for a single SVG path.
  5. * This binding handler will be registered as cesiumSvgPath.
  6. *
  7. * <p>
  8. * The parameter to this binding is an object with the following properties:
  9. * </p>
  10. *
  11. * <ul>
  12. * <li>path: The SVG path as a string.</li>
  13. * <li>width: The width of the SVG path with no transformations applied.</li>
  14. * <li>height: The height of the SVG path with no transformations applied.</li>
  15. * <li>css: Optional. A string containing additional CSS classes to apply to the SVG. 'cesium-svgPath-svg' is always applied.</li>
  16. * </ul>
  17. *
  18. * @namespace SvgPathBindingHandler
  19. *
  20. * @example
  21. * // Create an SVG as a child of a div
  22. * <div data-bind="cesiumSvgPath: { path: 'M 100 100 L 300 100 L 200 300 z', width: 28, height: 28 }"></div>
  23. *
  24. * // parameters can be observable from the view model
  25. * <div data-bind="cesiumSvgPath: { path: currentPath, width: currentWidth, height: currentHeight }"></div>
  26. *
  27. * // or the whole object can be observable from the view model
  28. * <div data-bind="cesiumSvgPath: svgPathOptions"></div>
  29. */
  30. const SvgPathBindingHandler = {
  31. /**
  32. * @function
  33. */
  34. register: function (knockout) {
  35. knockout.bindingHandlers.cesiumSvgPath = {
  36. init: function (element, valueAccessor) {
  37. const svg = document.createElementNS(svgNS, "svg:svg");
  38. svg.setAttribute("class", svgClassName);
  39. const pathElement = document.createElementNS(svgNS, "path");
  40. svg.appendChild(pathElement);
  41. knockout.virtualElements.setDomNodeChildren(element, [svg]);
  42. knockout.computed({
  43. read: function () {
  44. const value = knockout.unwrap(valueAccessor());
  45. pathElement.setAttribute("d", knockout.unwrap(value.path));
  46. const pathWidth = knockout.unwrap(value.width);
  47. const pathHeight = knockout.unwrap(value.height);
  48. svg.setAttribute("width", pathWidth);
  49. svg.setAttribute("height", pathHeight);
  50. svg.setAttribute("viewBox", `0 0 ${pathWidth} ${pathHeight}`);
  51. if (value.css) {
  52. svg.setAttribute(
  53. "class",
  54. `${svgClassName} ${knockout.unwrap(value.css)}`
  55. );
  56. }
  57. },
  58. disposeWhenNodeIsRemoved: element,
  59. });
  60. return {
  61. controlsDescendantBindings: true,
  62. };
  63. },
  64. };
  65. knockout.virtualElements.allowedBindings.cesiumSvgPath = true;
  66. },
  67. };
  68. export default SvgPathBindingHandler;