Creating classes and instances programmatically
Imagine we wish for our website to provide some information about the people who have visited it.
First, follow the recipe for PersistingObjects, then edit the Main javascript instance to read:
zimki.library.require('trimpath.js');
// create a class called Visitor if it doesn't exist yet
try {
zimki.persist.create('Visitor');
}
// if the class already exists, we'll get a zimki.error.class exception, which
// we can safely ignore.
catch(e) {}
function hello(args) {
var data = {};
// a different way to do defaults
data.who = !args.who ? 'Superman' : args.who;
// create a new instance for the current visitor
var person = Visitor.create({ where:'uk', name: data.who });
var pagecount = Counter.search({ name: 'page' })[0];
pagecount.count++;
pagecount.save();
data.pagecount = pagecount.count;
return zimki.render.trimpath('hello', data );
}
zimki.publishPath("/", hello);
Next, visit your website. Try visiting several times, with the parameter who set to different values, e.g.: appending '?who=Bob ' or '?who=Steve ' to the url for your site.
Now visit the Classes section in the portal. There should be a new class listed under Customer Classes called Visitor . Click on this class to see the its instances. It should have an instance for each time you visited the website.
Click on one of the instances. You will notice that it has the attributes name and where ; the latter should be set to uk , the former should be set to whatever you passed in the who attribute to the page, or Superman if you didn't pass anything.
Next step
Try to amend the code to not create duplicate entries, but instead maintain a count of how many times that particular person has visited the page.
See also
Parent
CookBook
|