In the portal, click on the Classes link in the application management bar. The
screen that appears shows all the classes that exists in your realm.
Click the Create button. Enter "Counter
" in the Class Name box in the form that appears. Don't worry about the other fields in the form yet; just hit the Create button. Your new class should show under the Customer Classes heading in the list of classes. Click on the class name to show instances of the Counter class (there won't be any yet).
Creating a counter through the portal
Let's create an instance of a Counter. Click the Create button in the 'Instances of Counter' view. Leave all the settings in the form that appears to their defaults and hit the Create button. Click on the ID of the instance that appears in the instance view. You should see a listing of an instance's default attributes; all instances have a creation_date
and a last_updated
attribute. In the Add/Edit Attribute form, create the following two new attributes (both of type string): { name: name, value: page } and { name: count, value: 1 }.
Creating a counter programmatically
Go to the JavaScript Console and type in the following code:
zimki.persist.create('Counter');
Counter.create({ name: 'page', count: 1});
Go to the Classes section and verify that you get the same result. Note that this won't work if you've already created the Counter class using the portal. You must delete the Counter class from the class list first in that case.
Searching for instances
Now let's make use of your counter instance. Assuming you have already created the HelloWorld.WithArguments example, go back and amend your javascript code to read:
// include the trimpath templating engine
zimki.library.require('trimpath.js');
function hello(args) {
var data = { who: 'Superman' };
if (args.who) data.who = args.who;
// search for an instance of the Counter class with
// 'page' as the value of its 'name' attribute.
// The search() method returns an array;
// grab the first element.
var pagecount = Counter.search({ name: 'page' })[0];
// increment the count, then save the instance again
pagecount.count++; // increment the pagecount
pagecount.save(); // make sure the increment takes hold
// assign the pagecount to the data we pass to the template
data.pagecount = pagecount.count;
return zimki.render.trimpath('hello', data );
}
zimki.publishPath("/", hello);
If you now visit your realm you should see that the pagecount will be increased every time you hit the page.
What did we do?
We first created a Zimki class called Counter. Instances of such classes are automatically stored by Zimki. We then added code to search for our counter and increment its count every time the hello function is called. We then pass the value of the counter instance to the template instead of simply passing 7 to it.
See also