ficus
ficus

Reputation: 304

JavaScript - updating / reinitialize object

I've got an "Product" object with values depending on each other like that:

function Product(object) {
  this.object = object;
  this.data = {
    id: this.object.val(),
  }
}

var product = new Product($('input[name="productId"]:checked'));

And... it is working. However, I would like to reinitialize whole object on input change, as I got few of them here:

 <input type="radio" name="productId" value="ONE" checked="checked" />
 <input type="radio" name="productId" value="TWO" />

I can set new value manually on change event:

$(function () {
  $('input[name="productId"]').change(function(e) {
    e.preventDefault();
    product.object = $('input[name="productId"]:checked');
  });
});

But it will only change 'object' value and won't affect other values in it.

I can of course set each new value by hand on change event, but doesn't seem right, does it?. I do not want to repeat myself eachtime I want to update that, I simply want to regenerate that object.

For now I have a workaround with public function in Product object and then call it on change event.

 this.updateData = function() {
   this.data.id = this.object.val();
 }

But again, it is just repeating each declaration and it's going to be pretty messy as more object properties than just an 'id' will appear.

Upvotes: 0

Views: 1590

Answers (1)

Michał Sałaciński
Michał Sałaciński

Reputation: 2266

Do you want to change every property of object? If that is the case, then why don't you create new object in place of old one?

$(function () {
  $('input[name="productId"]').change(function(e) {
    e.preventDefault();
    product = new Product($('input[name="productId"]:checked'));
  });
});

But if you wish to keep the object for some reason, you could do something like that:

function Product(object) {
  this.updateData = function(o) {
    this.object = o;
    if (!this.data) this.data = {};
    this.data.id = this.object.val();
    //etc...
  }
  this.updateData(object)
}

Upvotes: 2

Related Questions