mvvm.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function MVVM(options) {
  2. this.$options = options || {};
  3. var data = this._data = this.$options.data;
  4. var me = this;
  5. // 数据代理
  6. // 实现 vm.xxx -> vm._data.xxx
  7. Object.keys(data).forEach(function(key) {
  8. me._proxyData(key);
  9. });
  10. this._initComputed();
  11. observe(data, this);
  12. this.$compile = new Compile(options.el || document.body, this)
  13. }
  14. MVVM.prototype = {
  15. $watch: function(key, cb, options) {
  16. new Watcher(this, key, cb);
  17. },
  18. _proxyData: function(key, setter, getter) {
  19. var me = this;
  20. setter = setter ||
  21. Object.defineProperty(me, key, {
  22. configurable: false,
  23. enumerable: true,
  24. get: function proxyGetter() {
  25. return me._data[key];
  26. },
  27. set: function proxySetter(newVal) {
  28. me._data[key] = newVal;
  29. }
  30. });
  31. },
  32. _initComputed: function() {
  33. var me = this;
  34. var computed = this.$options.computed;
  35. if (typeof computed === 'object') {
  36. Object.keys(computed).forEach(function(key) {
  37. Object.defineProperty(me, key, {
  38. get: typeof computed[key] === 'function'
  39. ? computed[key]
  40. : computed[key].get,
  41. set: function() {}
  42. });
  43. });
  44. }
  45. }
  46. };