venter venter - 1 year ago 67
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.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) {

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

constructor() {

this.state = {
items: ShoppingCartStore.items


ShoppingCartStore.removeEventListener(?, ?);

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

render() {
return (
<h1>Shopping Cart</h1>
<table className="pure-table">
{, i) => <ShoppingCartRow key={i} index={i} item={item}/>) }
<ShoppingCartSumRow />

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 Source

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

var callbackReference;
     callbackReference = this.refresh.bind(this);

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download