Reputation: 117
I've gotten this to work but I would like to know if there is a straightforward way of accomplishing the update. I have a div where a data attribute has been assigned. When the div is clicked, I want one of the properties on the data attribute to be updated.
http://jsfiddle.net/quint/fq7dwsyv/
var originalObj = {
"x": 5,
"y": 58,
"selected": 'no'
};
var originalObjString = JSON.stringify(originalObj); // Convert object to JSON string
$('#test').attr('data-objData', originalObjString); // Attach data attribute to div
$('#test').on('click', function(event) {
var originalData = $(this).attr('data-objData'); // Store data attribute value
var originalDataJSON = JSON.parse(originalData); // Convert string to object
originalDataJSON['selected'] = 'yes'; // Update object property
var updatedData = JSON.stringify(originalDataJSON); // Convert object to string and store
$('#test').attr('data-objData', updatedData); // Update data attribute on div
});
Upvotes: 0
Views: 1256
Reputation: 350167
You can store the original object with .data()
and mutate it directly without having to store it again with the .data()
method:
var originalObj = {
"x": 5,
"y": 58,
"selected": 'no'
};
$('#test').data('objData', originalObj);
$('#test').on('click', function(event) {
$(this).data('objData')['selected'] = 'yes';
console.log($(this).data('objData'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test me</button>
The above solution assumes you are willing to change the way the object is stored with the element. If on the other hand the value must be stored on an element attribute, then there is not much that can be improved in your code. The steps you take are then all necessary (convert from/to JSON, read from attribute, write to attribute, ...etc).
Note however that writing to element attributes is not considered best practice. If anything, you should use .prop()
in favour of .attr()
: it will result in faster code. But you'll not see the change when consulting the element attributes. In other words, you cannot mix .prop()
with .attr()
.
If there is no room for change in that either, then I would suggest that you ask this question on CodeReview.
Upvotes: 0
Reputation: 52501
I'd separate the update into its own function
$('[data-example]').click(function() {
function update(object) {
object.foo = 'bar';
return object;
}
var original = this.dataset.example;
original = original && JSON.parse(original) || {};
this.dataset.example = JSON.stringify(update(original));
});
Upvotes: 1