I have an object with some information. On the other hand I have a store, holding many objects of this object type.
The single object should be able to delete itself from this store. My store knows a function "DeleteObjectFromStore" with a parameter of this object. Now I want to pass in the object itself but I don't know which syntax to use.
The store:
class NoteStore {
constructor() {
this.notes = []; // Collection of all notes
}
DeleteNote(note) { // Delete this object from the store
var index = this.notes.indexOf(note);
if (index > -1)
array.splice(index, 1);
}
}
And my object
class Note {
constructor(noteTitle, noteText, noteStore) {
this.title = noteTitle; // name
this.text = noteText; // content
this.store = noteStore; // dataStore
}
CreateDeleteButton(parentDiv) { // Create a button for deleting itself
var data = this.store;
var deleteBtn = document.createElement("input");
deleteBtn.type = "button";
deleteBtn.value = "Delete";
deleteBtn.onclick = function() {
data.DeleteNote(); // <= missing parameter!
}
parentDiv.appendChild(deleteBtn);
}
}
So using the keyword this is not correct. Then I would pass in the button.
Could someone help me out?
Try using a name for this outside the function:
CreateDeleteButton(parentDiv) { // Create a button for deleting itself
var data = this.store;
var noteObj = this;
var deleteBtn = document.createElement("input");
deleteBtn.type = "button";
deleteBtn.value = "Delete";
deleteBtn.onclick = function() {
data.DeleteNote( noteObj );
}
parentDiv.appendChild(deleteBtn);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.