updchg.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // UMD as of 14 May 2015 from github/umdjs/umd.
  2. (function (root, factory) {
  3. if (typeof define === 'function' && define.amd) {
  4. // AMD. Register as an anonymous module.
  5. define([], factory);
  6. } else if (typeof exports === 'object') {
  7. // Node. Does not work with strict CommonJS, but
  8. // only CommonJS-like environments that support module.exports,
  9. // like Node.
  10. module.exports = factory();
  11. } else {
  12. // Browser globals (root is window)
  13. root.returnExports = factory();
  14. }
  15. }(this, function () {
  16. function mixin(src, dst) {
  17. Object.keys(src).forEach(function (k) {
  18. if (typeof src[k] === "undefined") delete dst[k];
  19. else dst[k] = src[k];
  20. });
  21. }
  22. function UpdChg(event, methodName) {
  23. // event name used; defaults to "changed"
  24. this.event = event || "changed";
  25. // method name to pass changes into; defaults to "modelChanged"
  26. this.methodName = methodName || "modelChanged";
  27. }
  28. // For jQuery-like events,
  29. // call this with appropriate wrapper function
  30. // (jQuery, zepto, ...) to get an instance
  31. // with proper 'update' and 'observe' to mix in:
  32. // var updChg = new UpdChg(...).jQuery(jQuery);
  33. UpdChg.prototype.jQuery = function ($) {
  34. var event = this.event,
  35. methodName = this.methodName;
  36. return {
  37. // update signalling; using jQuery-like events
  38. // mix in: `ModelClass.prototype.update = updChg.update;`
  39. update: function (data) {
  40. mixin(data, this);
  41. $(this).trigger(event, data);
  42. },
  43. // observing; using jQuery-like events
  44. // mix in: `ViewClass.prototype.observeModel = updChg.observe;`
  45. // and make view instance call it once at the startup,
  46. // or, just make observing externally: `updChg.observe.call(view, model);`
  47. observe: function (model) {
  48. var self = this;
  49. $(model).on(event, function (ev, data) {
  50. self[methodName](data, this);
  51. });
  52. }
  53. };
  54. };
  55. return UpdChg;
  56. }));