SvgPathBindingHandler.js 3.0 KB

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