0

req.user.hails[0] is an instance of the class hails, it has the method cancel() I call it like this:

req.user.hails[0].cancel()

Can I from inside that instance remove the item itself?

    cancel: function() {
        //this will remove the item from a databae
        this.destroy()
        //Here I want to delete "this".
    }

The desired result is that req.user.hails.length is one shorter than before. I know I can remove it from where I'm calling cancel.

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • 2
    No, you have to remove it from the list. The code in `cancel()` can do that if it knows what array it's part of, but that would be a pretty fragile design in most cases. Objects don't "know" where references to themselves might be found, in general. – Pointy Jul 14 '16 at 14:30
  • Ideally `cancel` should set some status or flag and then you should used all elements which do not have this flag. – Rajesh Jul 14 '16 at 14:32

1 Answers1

0

No, you can't, not unless it happens (which is unlikely) that cancel closes over req, req.user, or req.user.hails. (And even then, it would be a really dodgy thing to do.) If it doesn't there's no information provided to your method that you can use to remove the entry from the array.

You could add a method to hails that both does the cancellation and removes the entry:

req.user.hails.cancelEntry = function(index) {
    this[index].cancel();
    this.splice(index, 1);
};

Yes, you can really add non-index properties to arrays like that. Note that they'll be enumerable, which is one reason not to use for-in loops to loop through arrays. (More about looping arrays in this question and its answers.)

You could make it non-enumerable:

Object.defineProperty(req.user.hails, "cancelEntry", {
    value: function(index) {
        this[index].cancel();
        this.splice(index, 1);
    }
});

In ES2015+, you could even create a subclass of Array that had cancelEntry on its prototype...

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875