I’m new in Dojo. However, I’m very lucky that the new 1.6 version introduces Memory and Observable classes.
Memory is part of the dojo.store namespace and it provides a data store that is implemented to store data in runtime. Together with Observable class (dojo.store.Observable) you can have a nice implementation of MVC.
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
type="text/javascript"></script>
<script>
dojo.require("dojo.store.Memory");
dojo.require("dojo.store.Observable");
dojo.ready(function() {
memory = new dojo.store.Memory();
observer = new dojo.store.Observable(memory);
// We define an attribute to sort the query results
query = observer.query(null, {sort: [{attribute: "order"}]});
query.observe(function(item, removedFrom, insertedInto) {
console.log(arguments);
if(removedFrom > -1){ // existing object removed
// Unfortunately, there is a bug in 1.6
// that sets removedFrom to the wrong index
// So, we use the item.id to find the node to
// remove
var node = dojo.byId("item" + item.id);
dojo.destroy(node);
}
if(insertedInto > -1){ // new or updated object inserted
dojo.place('<div id="item' + item.id + '">' + item.text + "</div>",
"container", insertedInto);
}
}, true);
// Adding "true" to observe method is very important
// to also observe object changes
// Put items (The order will determine how they
// are added to the DOM structure)
memory.put({id: 1, order: 1, text: "Test 1"});
memory.put({id: 2, order: 2, text: "Test 2"});
memory.put({id: 3, order: 4, text: "Test 3"});
memory.put({id: 4, order: 3, text: "Test 4"});
memory.put({id: 5, order: 5, text: "Test 5"});
// Removing item
memory.remove(4);
// Updating the order of an item
var item = memory.get(3);
item.order = 6;
memory.put(item);
// Changing the text of an item
var item = memory.get(2);
item.text = "Test 2 Changed";
memory.put(item);
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
The code block above shows an example usage of Memory and Observable to add new div elements to #container div when a new item is added to the memory store. Thanks to the listener function defined in query.observe call, any alteration to memory store is reflected in the #container div.
Beside making it much easier to deal with data changes, if you define query conditions (see “… observe.query(null,…” part) for the query call, when a new item is added to the memory store, if the query conditions are not met for this item, it won’t trigger the listener function call.
You can find more details at http://dojotoolkit.org/reference-guide/dojo/store/Memory.html.