mirror.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. define(function(require, exports, module) {
  2. "use strict";
  3. var Range = require("../range").Range;
  4. var Document = require("../document").Document;
  5. var lang = require("../lib/lang");
  6. var Mirror = exports.Mirror = function(sender) {
  7. this.sender = sender;
  8. var doc = this.doc = new Document("");
  9. var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
  10. var _self = this;
  11. sender.on("change", function(e) {
  12. var data = e.data;
  13. if (data[0].start) {
  14. doc.applyDeltas(data);
  15. } else {
  16. for (var i = 0; i < data.length; i += 2) {
  17. if (Array.isArray(data[i+1])) {
  18. var d = {action: "insert", start: data[i], lines: data[i+1]};
  19. } else {
  20. var d = {action: "remove", start: data[i], end: data[i+1]};
  21. }
  22. doc.applyDelta(d, true);
  23. }
  24. }
  25. if (_self.$timeout)
  26. return deferredUpdate.schedule(_self.$timeout);
  27. _self.onUpdate();
  28. });
  29. };
  30. (function() {
  31. this.$timeout = 500;
  32. this.setTimeout = function(timeout) {
  33. this.$timeout = timeout;
  34. };
  35. this.setValue = function(value) {
  36. this.doc.setValue(value);
  37. this.deferredUpdate.schedule(this.$timeout);
  38. };
  39. this.getValue = function(callbackId) {
  40. this.sender.callback(this.doc.getValue(), callbackId);
  41. };
  42. this.onUpdate = function() {
  43. // abstract method
  44. };
  45. this.isPending = function() {
  46. return this.deferredUpdate.isPending();
  47. };
  48. }).call(Mirror.prototype);
  49. });