SvgPathBindingHandler.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var svgNS = 'http://www.w3.org/2000/svg';
  2. var 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. * @exports 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. var SvgPathBindingHandler = {
  31. register : function(knockout) {
  32. knockout.bindingHandlers.cesiumSvgPath = {
  33. init : function(element, valueAccessor) {
  34. var svg = document.createElementNS(svgNS, 'svg:svg');
  35. svg.setAttribute('class', svgClassName);
  36. var pathElement = document.createElementNS(svgNS, 'path');
  37. svg.appendChild(pathElement);
  38. knockout.virtualElements.setDomNodeChildren(element, [svg]);
  39. knockout.computed({
  40. read : function() {
  41. var value = knockout.unwrap(valueAccessor());
  42. pathElement.setAttribute('d', knockout.unwrap(value.path));
  43. var pathWidth = knockout.unwrap(value.width);
  44. var pathHeight = knockout.unwrap(value.height);
  45. svg.setAttribute('width', pathWidth);
  46. svg.setAttribute('height', pathHeight);
  47. svg.setAttribute('viewBox', '0 0 ' + pathWidth + ' ' + pathHeight);
  48. if (value.css) {
  49. svg.setAttribute('class', svgClassName + ' ' + knockout.unwrap(value.css));
  50. }
  51. },
  52. disposeWhenNodeIsRemoved : element
  53. });
  54. return {
  55. controlsDescendantBindings : true
  56. };
  57. }
  58. };
  59. knockout.virtualElements.allowedBindings.cesiumSvgPath = true;
  60. }
  61. };
  62. export default SvgPathBindingHandler;