How do I update one value within an object using setAttribute?

混江龙づ霸主 提交于 2019-12-12 04:31:10

问题


I have an element that contains an attribute called "sound". The value of this sound attribute is an object. One of the properties in this object is "volume".

In other words:

<a-entity position='0 0 0' sound='src: url; on: click; volume: 2.0;'></a-entity>

So it's like this:

{
  position: '0 0 0',
  sound: {
    src: 'url',
    on: 'click',
    volume: '2.0'
  }
}

I'm using setAttribute to update the volume attribute but I don't know if there's an effective way to only target one property while not changing the other properties in the object.

Basically this replaces the sound object and removes all the properties that are not specified (src AND on properties are removed):

element.setAttribute('sound', {
  volume: '4'
});

I don't want to replace the entire object. I only want to replace one value for one property. Is there a best way to go about this?


回答1:


You can make use of the 3-argument version of setAttribute which is in the docs here: https://aframe.io/docs/core/entity.html#Updating-Multi-Property-Component-Data

Specifically you can do something like:

element.setAttribute("sound", "volume", "4");



回答2:


You could get object corresponding to the attribute, and replace only the properties you need.

Something like this:

var data = element.getAttribute('sound');
data.volume = '4';
element.setAttribute('sound', data);

Edit

If you set the data in the html like a real JS object, you could do:

var newData = JSON.parse(element.getAttribute('sound'));
newData.volume = 4;
element.setAttribute('sound', JSON.stringify(newData));

Here is a fiddle



来源:https://stackoverflow.com/questions/36568225/how-do-i-update-one-value-within-an-object-using-setattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!