Is circular referencing required in this situation?

  softwareengineering
class ItemList {  
   constructor() {
     this.list = [];//list holds many instances of Item Class
   }
   
   removeItem(id) {
   //...search for item in this.list, remove it
   }
}

class Item {   
    constructor(parent) {
    this.id = 123456;
    this.parent = parent;//ItemList
    }

    removeSelf() {
        this.parent.removeItem(this.id);
    }
}

The item class is able to delete itself and the state of ItemList is updated.

Is circular referencing required?

What design pattern(s) can address this?

6

Although you seem to have changed your mind there is a solution to this problem and its ‘events’

we have to be a bit careful in javascript because ‘events’ and ‘event handling’ in javascript normally refer to DOM events like button.onClick() But here we want to add events to our own objects.

We can use a pub sub pattern to make the framework which I won’t attempt to detail here but look at this example : https://www.npmjs.com/package/pubsub-js

Then you have your list and item classes

class ItemList {  
   constructor() {
     this.list = [];//list holds many instances of Item Class
     pubSub.ListenFor('RemoveItem', this.removeItem);
   }
   addItem(item) {
      this.list.add(item)
   }
   removeItem(id) {
   //...search for item in this.list, remove it
   }
}



class Item {   
    constructor() {
    this.id = 123456;
    }

    RemoveFromLists() {
        pubSub.Publish('RemoveItem', this.Id);
    }
}

Now, when RemoveFromLists is called, the item will be removed from any lists its been added to.

Really you want only to call listeners on lists where it’s actually been added, which you can do with a more complex pub sub pattern, or by passing the id around more.

I think you are making your data structure more complicated than it needs to be by adhering to a class based approach in the spirit of doing things object oriented.

A more logical way would be using an array. It already has all the required operations built-in:

const items = [{ id: 1 }, { id: 2 }, { id: 3 }] // Items
items.push({id: 4}) // Add item
items.splice(items.findIndex(item => item.id === 2), 1) // Remove item by id

Alternatively, without mutating the original array:

let items = [{ id: 1 }, { id: 2 }, { id: 3 }] // Items
items = items.concat({id: 4}) // Add item
items = items.filter(item => item.id !== 2) // Remove item by id

LEAVE A COMMENT