Note that there are some explanatory texts on larger screens.

plurals
  1. POObject Reference Persisting Beyond Variable Declaration
    primarykey
    data
    text
    <p>I'm building up a client-side collection of data to post to a server. Using the onClick event of an Add button, I'm collecting the form data and storing it in an internal array. This is some faux/sample code to try to demonstrate the issue (I can't share the source, unfortunately).</p> <pre><code>var getDataFromForm = (function() { var _internal = {}; /* Based on feedback, I think this is the reason for the behavior I'm experiencing */ return function() { var form = {}; /* Get the form data */ _internal.name = form.name; _internal.id = form.id; return _internal; }; }()); var internal = { vals: [] }; function onClick() { var newData = getDataFromForm(); doAjaxValidation({ success: function() { internal.vals.push(newData); /* All values in array have been updated to this newData reference on click */ internal.vals.push( JSON.parse(JSON.stringify(newData)) ); /* ugly, but the reference is broken and future clicks work as expected */ internal.vals.push( $.extend({}, newData) ); /* reference to the object is still persisted through jQuery's extend */ } }); } </code></pre> <p>I'm confused as to why the <code>newData</code> reference is handed to the new assignment of <code>newData</code> each button click. Each click event is a new function call and <code>newData</code> (theoretically) should be a new object which is not related to the <code>newData</code> from any other button click.</p> <p>What am I missing?</p> <p>Edit: this sample is from a much larger block of code, and I tried to reduce it to the simplest possible expression. Obviously, as-is, this is not a functional piece of code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload