venter venter - 1 month ago 5
React JSX Question

How can i find out, what listener to unregister?

The problem is the following:

I got a listener on a array of callback's. They look like this:

static listeners = [];


They're in a js-file that adds and removes items of a array.

static items = [];
static listeners = [];

static add(item) {
this.items.push(item);
this.listeners.forEach((callback) => callback());
};

static remove(item) {
var index = this.items.indexOf(item);
this.items.splice(index, 1);
this.listeners.forEach((callback) => callback());

};

static register(callback) {
this.listeners.push(callback);
};


I want to let a component know when the array changes and to re-render by setting state.

constructor() {
super();

this.state = {
items: ShoppingCartStore.items
};
}

componentWillMount(){
ShoppingCartStore.register(this.refresh.bind(this));
}

componentWillUnmount(){
ShoppingCartStore.removeEventListener(?, ?);
}

refresh() {
this.setState({items: ShoppingCartStore.items})
}

render() {
return (
<div>
<h1>Shopping Cart</h1>
<table className="pure-table">
<thead>
<tr>
<td>No</td>
<td>Item</td>
<td>Size</td>
<td>Price</td>
<td></td>
</tr>
</thead>
<tbody>
{this.state.items.map((item, i) => <ShoppingCartRow key={i} index={i} item={item}/>) }
<ShoppingCartSumRow />
</tbody>
</table>
</div>
);
}


Other components listen on this array of listeners as well.

How can i find out what listener should be unregister?

I have to unregister the listener because i want to return to the main page where items are selected by customer and react can't setState on a unmounted component.

Thanks for any input and i apologize for my bad english

Answer

You can keep a reference to the callback function that you pass to register:

var callbackReference;
componentWillMount(){
     callbackReference = this.refresh.bind(this);
     ShoppingCartStore.register(callbackReference);
}

And then, you can write the removeEventListener function like this:

static removeEventListener(reference){
    var index = this.listeners.indexOf(reference);
    if(index != -1){
        this.listeners.splice(index, 1);
    }
}

And here is how you'll call it:

componentWillUnmount(){
    ShoppingCartStore.removeEventListener(callbackReference);
}
Comments