⬆️ ⬇️

Fun State Management Huex Framework

image



Introduction



It always amazed me how many actions need to be done for state management frameworks - to immediately describe the scheme, write mutations, commit them ... Why not do everything minimally simple?)



Why write code when you can not write?

')

(updated)

I present to you my half hour hack - Huex !



So far, the solution is available only on the NodeJS platform, but for the presentation I think that will be enough.



Disclaimer: Huex is written by me only for entertainment and educational purposes and does not claim to be a full-fledged framework. And maybe he claims. And now let's go.



What is it for?



Have a single convenient data storage. Have the ability to monitor their changes. He will get rid of incomprehensible words like “getters”, “mutators”, “actions”, “commit”, etc.



How to install it?



So far, just copying this repository.

After the repository is copied, it needs to be connected via your project’s package.json somewhere like this:



"dependencies": { "huex": "file:../huex/" } 


After that, it will be available as a “huex” module.



Or make it even easier, as dpr correctly noted:

npm i -S https://github.com/vssenko/huex.git



How to use it?



The most natural and simple. Let's start right away with the code:



 //  huex. const Huex = require('huex'); //  . const storage = Huex(); //     - . storage.on('change:a', (e) => console.log(`Property "a" was changed: ${e.value}`)); //      . storage.a = 5; 


And it's all. When any change \ setting field of our store will create two events: change with data {key, value} and change: key with data {value}.

(updated)

And for nested objects and arrays, events will be created both on the nested object and on the parent.

Enough to create projects of any complexity.



Maybe something else?



Of course: you can create deeply nested fields on the go, and no exceptions will be created.



 const Huex = require('huex'); const storage = Huex(); storage.abcde = 5; 


And, of course, it is also possible to hang event handlers on all nested objects.



(updated)

Maybe something else?



Yes! Now Huex works not only with simple data, but also with objects and arrays, on the move remaking them in Huex-storage!

  sut.subSut = { a: 5 }; sut.on('change:subSut', (e) => { console.log(e.key); // subSut console.log(e.value.a) // 10 console.log(e.nested); // { key: 'a', value: 10 } }); sut.subSut.a = 10; 




More examples are available in project tests.



What's the catch?



All this magic is implemented through Proxy . And this is not the fastest solution, and in general they do not recommend using the Proxy class in production.



(update)

Conclusion



During the two cycles (evenings) of development, the JS-community has another interesting framework.

What Huex can do:



What Huex Can't Do:

Source: https://habr.com/ru/post/421783/



All Articles