Syntax
var name = new zpt.ReactiveDictionary( object, [ autoCommit ] );
Description
Defines a dictionary with reactive capabilities: it can detect some type of modifications done to it and invoke an update command. The parameters are:
- object (object). An object with the values to show in the template.
- autoCommit (boolean, default is
true
). Defines if ZPT will run an update command automatically after each change. If it isfalse
no action will be done until a commit command is executed.
When a ReactiveDictionary is instanced ZPT-JS walks through all of the properties of the object and creates getters and setters using Object.defineProperty
inside the ReactiveDictionary: the original object is not modified.
The avaliable methods are:
- _isAutoCommit(). Returns a boolean value,
true
is auto commit mode is on,false
otherwise. - _setAutoCommit( autoCommit ). Updates the auto commit mode.
- _commit(). Commits changes. It does nothing if the auto commit mode is on (there is noaction to commit).
- _addVariable( key, value ). Useful to add a new entry to the dictionary. It is needed for adding the getter and the setter to the dictionary.
- _addActions( dictionaryActions ). Add some special actions to the dictionary. They include add, edit and remove elements in an array or edit and remove element in an object. For more details about dictionary actions go to reference or tutorial.
Examples
An example of use:
"use strict"; var zpt = require( 'zpt' ); var dictionary = new zpt.ReactiveDictionary({ message: 'Hello, world!' }); // Parse template zpt.run({ root: document.body, dictionary: dictionary });
If we change some data in the dictionary this way:
dictionary.message = "Bye, world!";
We don't need to do anything else, the HTML code will be updated.
More examples. If we want to do some changes but only one update of HTML we must set the auto commit to off:
"use strict"; var zpt = require( 'zpt' ); var dictionary = new zpt.ReactiveDictionary( { message1: 'Hello, world1!', message2: 'Hello, world2!', message3: 'Hello, world3!' }, false ); // Parse template zpt.run({ root: document.body, dictionary: dictionary });
Now we modify some variables, but ZPT will not update HTML until commit is done:
dictionary.message1 = 'Bye, world1!'; dictionary.message2 = 'Bye, world2!'; dictionary.message3 = 'Bye, world3!'; dictionary._commit();
We can activate or deactivate auto commit mode whenever we want:
dictionary._setAutoCommit( true ); dictionary.message1 = 'Hello again, world!';
ZPT will update HTML after the change of the value of message1
. Be careful, pending updates will also be done!