Przeglądaj źródła

Add typedAction.

Herbert Vojčík 8 lat temu
rodzic
commit
2632f3427d
5 zmienionych plików z 55 dodań i 0 usunięć
  1. 22 0
      README.md
  2. 12 0
      lib/node.js
  3. 15 0
      lib/typed-action.js
  4. 1 0
      src/node.js
  5. 5 0
      src/typed-action.js

+ 22 - 0
README.md

@@ -108,3 +108,25 @@ using `[...obj]`, not using `{...obj}`.
 
 That way you can create eg. `const c = cowValueObject("person", 34, "name")`
 to access `obj.person[34].name` with `c(obj)` / `c(obj, val)`.
+
+### `typedAction(type, fn)`
+
+This creates an action creator function that amend existing `fn` by:
+  - adding a `type` property to the result, as well as
+  - adding a `TYPE` property to action creator itself.
+
+So for example:
+
+```js
+export const answerQuestion =
+    typedAction("answer question", (index, answer) => ({
+        payload: {index, answer}
+    }));
+```
+
+allows you to call `answerQuestion(2, "Albert Einstein")` to create
+`{type: "answer question", payload: {index: 2, answer: "Albert Einstein"}}`;
+but it also allows you to use `case answerQuestion.TYPE:` in your reducer,
+since `answerQuestion.TYPE === "answer question"`.
+IOW, this removes the two-space problem of having `const FOO_BAR_TYPE`
+as well as `fooBar` action creator.

+ 12 - 0
lib/node.js

@@ -26,4 +26,16 @@ Object.keys(_cowValueModel).forEach(function (key) {
       return _cowValueModel[key];
     }
   });
+});
+
+var _typedAction = require('./typed-action');
+
+Object.keys(_typedAction).forEach(function (key) {
+  if (key === "default" || key === "__esModule") return;
+  Object.defineProperty(exports, key, {
+    enumerable: true,
+    get: function get() {
+      return _typedAction[key];
+    }
+  });
 });

+ 15 - 0
lib/typed-action.js

@@ -0,0 +1,15 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+    value: true
+});
+
+var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
+
+var typedAction = exports.typedAction = function typedAction(type, fn) {
+    var result = function result() {
+        return _extends({}, fn.apply(undefined, arguments), { type: type });
+    };
+    result.TYPE = type;
+    return result;
+};

+ 1 - 0
src/node.js

@@ -1,2 +1,3 @@
 export * from './sac';
 export * from './cow-value-model';
+export * from './typed-action';

+ 5 - 0
src/typed-action.js

@@ -0,0 +1,5 @@
+export const typedAction = (type, fn) => {
+    const result = (...args) => ({...fn(...args), type: type});
+    result.TYPE = type;
+    return result;
+};