Autosync
work with data, not with DOM
Download
autosync.jsStandard version: IE 9+, Firefox 4.0+, Opera 12.1+, Chrome 5.0+
autosync-compat.jsExtended version: IE 6+, Firefox 1.0+, Opera 8.0+
Events

As Autosync updates DOM elements periodically replacing them with new ones, there is a problem of preserving event handlers attached to these elements.

Though you can use after hooks to attach event handlers after each update by yourself, Autosync offers a better way.

You can create your own handlers either in special funcs object inside the context where the model is stored, or inside the context itself, if it is convinient for you. This brings strict and easy to understand structure into the code by grouping each module's function together in one place. After that you can assign handlers to arbitrary elements inside templates with as-on[event] attributes:


context.myFunc = function(str) {
   /* ... */
   return str
}
               

<div class="description" as-onclick:stop="console.log(myMethod(this.textContent))">
   {$value['description']}
</div>
               

Notice the stop modifier used after :. This modifier stops the event propagation up the DOM tree (though you can do it in the code of your handler function directly, if you want). The following modifiers are supported at the moment:

stopPrevents the event's propagation
preventPrevents the default browser action
captureAssigns event handler in capture mode
selfCalls handler only if event target equals to current element

Special values $value, $index and $event are available inside the handler, also if there are elements with asref attribute in current template, all of them are also available via that attribute's values prefixed with $ sign.

The fact that methods called inside event handlers are stored inside the context and not the model allows to keep the model and its prototype clean, holding only the data and a few service methods in it, and also it allows you to use your methods in several different models stored inside a single context.

After each DOM update the handlers will be reassigned for the new DOM elements.

Also you can assign and remove event handlers with the API methods:


as.addEvent(module, scope, selector, type, func, key)
as.clearEvents(module, scope, selector, type, func)
               

addEvent method expects model name, its context (scope), CSS selector for target elements selection, event type and the handler function. Dynamically assigned andlers are called after the as-on* attribute assigned handler and in the same order as they were registered. When each handler is called it is passed the event object event, the model value value, its context scope and its index in the list index (if model is not a list member the index is -1).

When deleting the handler it is possible to provide the exact handler function or to delete all handlers of the given type.