Reputation: 11607
I've created a class to hold an interface component on one of my web pages. There is an add
button to instantiate the class and insert the new element into the DOM. I want to give the class a remove
method to remove the element from the dom, and then destroy the instance.
I have this:
// can have multiple tags
var Tag = new Class({
Implements: [Options, Events],
this.targetElement: undefined,
this.tagName: undefined
initialize: function() {
this.targetElement = new Element('input', { class: 'tag' });
this.targetElement.inject($('tagHolder'));
...
// event handler to set `this.tagName` to contents of the input
...
if (Tag.tags === undefined)
Tag.tags = [];
Tag.tags.push(this);
},
remove: function () {
this.targetElement.destroy();
delete this;
}
this removes the element from the DOM, but does not delete the instance object.
I want to use the array tag.tags
to get access to all the tags the user has created, so if the user deletes a tag, I want that tag to be removed from the array, or be set to undefined
, or similar. As the tag instance is then no longer needed, it makes sense to delete/prepare for GC the object at this point so that memory isn't wasted.
How should I do this, or is this a silly method? Is there a better way?
Upvotes: 0
Views: 1000
Reputation: 26165
you should be able to use Array.erase
w/o any problems.
change your remove method to:
remove: function () {
this.targetElement.destroy();
Array.erase(Tags.tags, this);
// reset reference
}
Upvotes: 1