0

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.

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

In fact, I tried first solution in the first place.. i just put "var product" instead of "product" inside of change event. Well, no idea why :-) Second solution will be also useful in future. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.