Contexts are "container" objects where your models are stored. Only the user defines the context, Autosync does notforce any requirements on it. Context can be defined by reference or by string, or it can be left undefined at all defaulting to window
.
Contexts allow Autosync to "know" your models' parent objects where it has to watch changes (in order for the updates to work on data = new_data
assignments). Also if the context defined using a string (and that means that it is globally accessible), it allows to split DOM elements with the same model name into groups and update just one of those groups. In other words this feature allows us to have several models with the same name (like data
) but different semantics and content: user.data
and dashboard.data
would be a realistic example of this.
Futhermore, if the context is accesible through the global scope you can include it right into the model name as its part:
<input type="text" class="email" asmodel="user.profile_data.email" />
Here user.profile_data
is the model name, а email
is the field that we are interested in. But we can also say that the model in this case is user
, and everything else is a path to the property field. Either way it will work correctly as you would expect. The update will happen when some property will change either in user.profile_data
or in user
.
When one of the parent objects of the model is reassigned, there will immanently happen excessive updates of extra elements whose content has not changed (if the reasssigned object itself or one of its parents is registered as a model) and which could have been skipped. But full update helps to keep code of Autosync simplier and more compact.
When one of che child objects inside the model changes its value, parent objects to not trigger updates of their elements by default. To change this behavior, e.g. to update the model's full JSON representation in some element, pass the fourth atomic
argument with the value true into the add
method.
But what if the context is defined inside a closure, and you don't want to expose it globally? Autosync has a solution for this case too. Pass the third argument key
on model registration, and in this case will be updated only elements which have asmodelkey
attribute and it's value either equals key
or equals "*".
<input type="text" class="email" asmodel="user.profile_data.email" askey="usr" />
// Creating the closure
(function() {
var data = { user: { name: 'admin', email: '[email protected]', active: true } }
as.add('user', data, 'usr')
})()
If the attribute askey
is not assigned, it is silently set to "*". If you want such element not to update, add the attribute as askey=""
.