Flux模式

简单的dispatcher实现

  1. var Dispatcher = function () {
  2. return {
  3. _stores: [],
  4. register: function (store) {
  5. this._stores.push({store: store});
  6. },
  7. dispatch: function (action) {
  8. if (this._stores.length > 0) {
  9. this._stores.forEach(function (entry) {
  10. entry.store.update(action);
  11. });
  12. }
  13. }
  14. }
  15. };

我们期望我们的store能提供一个update方法. 接下来让我们来修改一下我们的register函数.

  1. function register(store) {
  2. if (!store || !store.update && typeof store.update === 'function') {
  3. throw new Error('You should provide a store that has an update method');
  4. } else {
  5. this._stores.push({store: store});
  6. }
  7. }

完整的dispatcher实现

  1. var Dispatcher = function () {
  2. return {
  3. _stores: [],
  4. register: function (store) {
  5. if (!store || !store.update && typeof store.update === 'function') {
  6. throw new Error('You should provide a store that has an `update` method.');
  7. } else {
  8. var consumers = [];
  9. var change = function () {
  10. consumers.forEach(function (l) {
  11. l(store);
  12. });
  13. };
  14. var subscribe = function (consumer, noInit) {
  15. consumers.push(consumer);
  16. !noInit ? consumer(store) : null;
  17. };
  18. this._stores.push({store: store, change: change});
  19. return subscribe;
  20. }
  21. return false;
  22. },
  23. dispatch: function (action) {
  24. if (this._stores.length > 0) {
  25. this._stores.forEach(function (entry) {
  26. entry.store.update(action, entry.change);
  27. });
  28. }
  29. }
  30. }
  31. };
  32. module.exports = {
  33. create: function () {
  34. var dispatcher = Dispatcher();
  35. return {
  36. createAction: function (type) {
  37. if (!type) {
  38. throw new Error('Please, provide action\'s type.');
  39. } else {
  40. return function (payload) {
  41. return dispatcher.dispatch({type: type, payload: payload});
  42. }
  43. }
  44. },
  45. createSubscriber: function (store) {
  46. return dispatcher.register(store);
  47. }
  48. }
  49. }
  50. };

参考资料: