Because templates in Autosync only have access to the data inside their model, there is often a problem of missing detailed data for the output if they are located inside another model. In other words, sometimes inside the data object that came from the server or some API there are only IDs that reference objects in another collection.
You can solve this problem by applying transform to the model in before hook, but Autosync allows to achieve it in much more convenient way.
data.states = [
{id: 1, name: 'New'},
{id: 2, name: 'Assigned'},
{id: 3, name: 'Finished' }
]
as.embedObject(window, 'data.states:id -> data.tasks:state_id:state')
Here we ask Autosync to create a copy of the object from collection states
with id
property equal to state_id
for each element of tasks
collection, and update that copy whenever states
changes. Notice: that copy is not reactive, so by changing it you will not change the source object (even more, in browsers that support Object.freeze it is read-only). You can use it however you like, event replace it or delete completely in any moment, but it will be recreated with the correct value when the source collection will update.
Note that the source and destination collections must be located inside the same context (though not neccessarily in the same registered by the add
method model).
There is alwo another one method of copying data from the object from another collection: it is a so-called property extraction. You can copy only the properties that you need by listing them inside square brackets separated with commas:
data.states = [
{id: 1, name: 'New'},
{id: 2, name: 'Assigned'},
{id: 3, name: 'Finished' }
]
as.embedObject(window, 'data.states:id -> data.tasks:state_id:[name]')
After >
symbol you can set the name for the newly created property; if you don't, it will be computed automatically as the source collection name in single form plus _
symbol plus source property name (state_name
in our example). If the source collection name in single form is the same as the sorce property name, then the destination name will be set to the source property name (the state
property of the object from states
collection will be copied into state
, and not state_state
).
data.states = [
{id: 1, state: 'New'},
{id: 2, state: 'Assigned'},
{id: 3, state: 'Finished' }
]
// is equivalent to data.states:id -> data.tasks:state_id:[state>state]
as.embedObject(window, 'data.states:id -> data.tasks:state_id:[state]')
If you don't need the embed anymore, you can remove it by calling removeEmbed
method:
removeEmbed(context, 'data.states:id -> data.tasks:state_id:state', false)
The last keep
argument allows to cancel the watching of the source collection but keep the emdeds themselves in their current state.