问题
What's the best way to load a custom JSON file as data into an A-frame component ? For example, the JSON file may contain coordinates of points. I want to load the file as an asset and use the parsed json object in the component.
{"coordinates": [{"x": 0, "y": 1, "z": 2}, // ...]}
回答1:
You can define your own property type in the schema that parses data how you wish.
To parse JSON from a component, create a parse
function that does a JSON.parse
:
AFRAME.registerComponent('foo', {
schema: {
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify
}
}
});
Then use the component:
el.setAttribute('foo', 'jsonData', yourJsonData);
Or:
<a-entity foo='jsonData: {"coordinates": [{"x": 0, "y": 1, "z": 2}]}'></a-entity>
回答2:
Another way is to set your component to have no schema so it just takes an object. There is no API to have a "wildcard" schema yet, but one way is to have a property type that parses the inline-CSS-like string with the styleParser:
AFRAME.registerComponent('foo', {
schema: {
parse: AFRAME.utils.styleParser.parse
}
});
The above component is a single-property schema, so whatever object we pass will become the value of this.data
:
el.setAttribute('foo', {bar: 'baz', qux: 'qaz', whateverWeWant: true});
Or:
<a-entity foo="bar: baz; qux: qaz: whateverWeWant: true"></a-entity>
来源:https://stackoverflow.com/questions/41545518/how-to-load-json-data-into-an-a-frame-component