Frederick M. Rogers
Frederick M. Rogers

Reputation: 921

JavaScript - Is there any way to dynamically create a new instance of a object?

I am working on a small project where by i need to create objects with form field data. In short i have a constructor function that retrieves values from each form field like this:

var Task = function() {
  this.title = document.getElementById("task-title").value;
  this.date = document.getElementById("task-date").value;
  this.option = document.getElementById("task-option").value;
}

What i need is create a NEW instance of object each time somebody clicks the submit button. What i have so far is this:

var submitBtn = document.getElementById('#someID');
submitBtn.addEventListener('click', function(event) {
   event.preventDefault();
   var newTask = new Task();           
});

This works in that it create an object, but the objects gets overridden each time the button is pressed. I need a new instance of the object to be created each time the buttoned is pressed.

Is this possible ? if not is there a more viable alternative to constructor functions? Thank you so much.

Upvotes: 0

Views: 1329

Answers (2)

RobbyD
RobbyD

Reputation: 513

You're defining that newTask variable inside the enventlistener and then immediately assigning the new Task to it. Your code is doing everything you told it to do. Namely, create a new variable and assign a new instance of task to it. After the function ends the newTask is destroyed because there's nothing to do anymore and nowhere else in your code are you able to reach it.

Why dont you try this:

var submitBtn = document.getElementById('#someID');
var myTasks = [];
submitBtn.addEventListener('click', function(event) {
  event.preventDefault();
  myTasks.push(new Task());           
});

Upvotes: 1

Johnny John
Johnny John

Reputation: 384

That's because you are always putting the value in the same var, you will need make a array with your objects, so you don't lose your old object

var submitBtn = document.getElementById('#someID');
var newTask = [];
submitBtn.addEventListener('click', function(event) {
   event.preventDefault();
   newTask.push(new Task());           
});

Upvotes: 1

Related Questions