jquery.sketchable.serializer.js

  1. /*!
  2. * Serializer plugin for Sketchable | v1.0 | Luis A. Leiva | MIT license
  3. */
  4. /* eslint-env browser */
  5. /* global jQuery */
  6. ;(function($) {
  7. // Custom namespace ID, for private data bindind.
  8. var namespace = 'sketchable';
  9. /**
  10. * Serializer plugin constructor for jQuery Sketchable instances.
  11. * @param {jQuery} $instance - jQuery sketchable instance.
  12. * @namespace $.fn.sketchable.plugins.serializer
  13. */
  14. $.fn.sketchable.plugins.serializer = function($instance) {
  15. // Expose public API: all jQuery sketchable instances will have these methods.
  16. $.extend($.fn.sketchable.api, {
  17. // Namespace methods to avoid collisions with other plugins.
  18. serializer: {
  19. /**
  20. * Save canvas data as JSON string.
  21. * @return {string}
  22. * @memberof $.fn.sketchable.plugins.serializer
  23. * @example
  24. * var contents = jqueryElem.sketchable('serializer.save');
  25. */
  26. save: function() {
  27. var data = $(this).data(namespace);
  28. // Save only the required properties.
  29. // Also avoid circular JSON references.
  30. return JSON.stringify({
  31. strokes: data.strokes,
  32. options: data.options,
  33. actions: data.sketch.callStack,
  34. });
  35. },
  36. /**
  37. * Load canvas data from JSON string.
  38. * @param {string} jsonStr - JSON data saved with {@link $.fn.sketchable.plugins.serializer.save} method.
  39. * @return {jQuery} jQuery sketchable element.
  40. * @memberof $.fn.sketchable.plugins.serializer
  41. * @example
  42. * jqueryElem.sketchable('serializer.load', jsonStr);
  43. */
  44. load: function(jsonStr) {
  45. var data = $(this).data(namespace);
  46. var origData = JSON.parse(jsonStr);
  47. var mySketch = data.sketch;
  48. for (var i = 0; i < origData.actions.length; i++) {
  49. var entry = origData.actions[i];
  50. if (entry.property && typeof entry.value !== 'object') {
  51. // Update graphics properties.
  52. mySketch.data[entry.property] = entry.value;
  53. } else if (entry.method) {
  54. mySketch[entry.method].apply(mySketch, entry.args);
  55. } else {
  56. console.warn('Unknown call:', entry);
  57. }
  58. }
  59. // Update required properties.
  60. data.sketch.callStack = origData.actions.slice();
  61. data.strokes = origData.strokes.slice();
  62. data.options = origData.options;
  63. return $instance;
  64. },
  65. },
  66. });
  67. };
  68. })(jQuery);