owja / ioc

:unicorn: lightweight (<1kb) inversion of control javascript library for dependency injection written in typescript
MIT License
287 stars 13 forks source link

Proposal: Subscribable (WIP) #22

Closed hbroer closed 2 years ago

hbroer commented 5 years ago

I am working with react and preact the most times, and one of the code i have to write over and over again is to subscribe to listener on componentWillMount or on the construction and unsubscribe on componentWillUnmount.

To fix this i am thinking about to implement some kind of automatism. Just telling the inject decorator to subscribe and it will do it for me.

class Subscribable {
    listener: (() => void)[] = [];

    listen(listener: () => void): () => void {
        this.listener.push(listener);
        return () => this.listener.splice(this.listener.indexOf(listener), 1);
    }

    trigger() {
        this.listener.forEach((cb) => cb());
    }
}

class Updateable extends Component {
    @inject(TYPE.subscribable, SUBSCRIBE)
    service!: Subscribable;
}

const updateable = new Updateable();

Component has the method forceUpdate() and can have componentWillUnmount().

When we access updateable.service it should subscribe to Subscribable. When ever trigger() is executed forceUpdate() on Updateable should get executed.

This is work in progress.

When Updateable will get unmounted and its method componentWillUnmount gets triggered, it should unsubscribe from Subscribable.

codecov[bot] commented 5 years ago

Codecov Report

Merging #22 into master will not change coverage. The diff coverage is 100%.

Impacted file tree graph

@@          Coverage Diff          @@
##           master    #22   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           3      3           
  Lines          53     75   +22     
  Branches        9     16    +7     
=====================================
+ Hits           53     75   +22
Impacted Files Coverage Δ
src/ioc/inject.ts 100% <100%> (ø) :arrow_up:
src/ioc/container.ts 100% <100%> (ø) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 935df56...03f037d. Read the comment docs.

hbroer commented 5 years ago

Feels like this eats too many bytes at the moment.

    854 B: ioc.js.gz
    733 B: ioc.js.br
    862 B: ioc.mjs.gz
    734 B: ioc.mjs.br
hbroer commented 2 years ago

I close this in favor of another solution