Dojo Tree based on ItemFileReadStore and parent-based model - javascript

I'm trying to programmatically create a dojo tree from a json file. The problem is that my json objects reference to their parents not children as in some examples.
Unfortunately my output looks only like this:
I have the following javascript code:
<script type="text/javascript">
require(["dijit/Tree", "dojo/data/ItemFileReadStore", "dijit/tree/ForestStoreModel", "dijit/tree/ObjectStoreModel", "dojo/domReady!"],
function(Tree, ItemFileReadStore, ObjectStoreModel, ForestStoreModel){
var store = new ItemFileReadStore({
url: "/_data/test.json",
getChildren: function(object){
return this.query({F_TopLevelCategoryID: object.P_CategoryID});
}
});
var myModel = new ObjectStoreModel({
store: store,
labelAttr:'CategoryName',
query: {"P_CategoryID": 0}
});
var myTree = new Tree({
model: myModel
}, "treeOne");
myTree.startup();
});
</script>
The json file looks like the following:
{ "identifier" : "P_CategoryID",
"label" : "CategoryName",
"items" : [ { "CategoryName" : "Category 1",
"F_TopLevelCategoryID" : 0,
"P_CategoryID" : 1
},
{ "CategoryName" : "Category 2",
"F_TopLevelCategoryID" : 1,
"P_CategoryID" : 2
},
{ "CategoryName" : "Category 3",
"F_TopLevelCategoryID" : 1,
"P_CategoryID" : 3
},
{ "CategoryName" : "Category 4",
"F_TopLevelCategoryID" : 1,
"P_CategoryID" : 4
},
{ "CategoryName" : "Category 5",
"F_TopLevelCategoryID" : 3,
"P_CategoryID" : 5
},
{ "CategoryName" : "Category 6",
"F_TopLevelCategoryID" : 4,
"P_CategoryID" : 6
},
{ "CategoryName" : "Category 7",
"F_TopLevelCategoryID" : 4,
"P_CategoryID" : 7
},
{ "CategoryName" : "Category 8",
"F_TopLevelCategoryID" : 0,
"P_CategoryID" : 8
},
{ "CategoryName" : "Top Level Category",
"P_CategoryID" : 0
}
]
}
Where is the problem?

I believe it was a fluke that you received a partial result.
You have forestStoreModel and objectStoreModel transposed in the require block, and referencing parents is fine!
Also, use dojo/store instead of ItemFileReadStore, as the latter is deprecated. Use the data parameter on Memory:
var store = new Memory({
data: testJson,
getChildren: ...
});
See my working fiddle here, using dojo/store/Memory: https://jsfiddle.net/yubp45sa/
You can get your data into the memory store using dojo/request:
request("testData.json").then(...);
http://dojotoolkit.org/reference-guide/1.10/dojo/request.html
I had another request example in previously, which requested the data through a GET from a custom nodeJS route (returning JSON):
request.get("/configInfo", {
handleAs: "json"
}).then(...);

Related

Mongodb mapreduce Join 2 collections

I have 2 collections and I am new to Mongo MapReduce concept.
My collection Value looks like this
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb7"),
"name" : "Title 1",
"value" : "value 1 for title 1"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb8"),
"name" : "Title 1",
"value" : "Value 2 for title1. "
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb9"),
"name" : "Title 2",
"value" : " Definitely a motivational text!"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccba"),
"name" : "Title 2",
"value" : "It's tough but I'm carrying on. "
}
Other collection Details look like:
{
"_id" : ObjectId("5bc4f2361a80d2045029d05b"),
"name" : "Title 1",
"totalValues" : 6.0000000000000000,
"link": "Link1",
"description" : "Some More Text to Make title 1 look better"
}
{
"_id" : ObjectId("5bc4f2361a80d2045029d2eb"),
"name" : "Title 2",
"totalValues" : 2,
"link": "Link2",
"description" : "Some More Text to Make title 2 look better"
} ...
I want the output result as
{
“name” : “XXXXXXXX”,
“comments” : [ {“value”: “XXXXXXX”}, {“value”: “YYYYYYYY”}],
“totalValues” : 2,
“link”: “XXXXXXXXXX”,
“description”: “XXXXXXXXXXXXXXXXXX”
}
with the following output document. Please help.
I have tried following code:
var mapDetails = function(){
var output = {name: this.name,totalValues :this.totalValues, description : this.description, link :this.link}
emit(this.name, output);
};
var mapGpas = function() {
emit(this.name,{name:this.name, value:this.value, totalValues:0, description: 0, link: 0});
};
var r = function(key, values) {
var outs = { name: 1,value: 1, description: 0,totalValues:0, link: 0};
values.forEach(function(v){
outs.name = v.name;
if (v.value == 0) {
outs.description = v.description;
outs.totalValues = v.totalValues;
outs.link = v.link;
}
});
return outs;
};
res = db.Value.mapReduce(mapGpas, r, {out: {reduce: 'joined'}})
res = db.Details.mapReduce(mapDetails, r, {out: {reduce: 'joined'}})
db.joined.find().pretty()

Building a tree structure in angularjs

I would like to build a tree dynamically in angularjs, the structure is retrieved as follows from the database.
[{
"TreeName":"String content",
"Level":0,
}],
[{
"TreeName":"String content",
"Level":0,
}],
[{
"TreeName":"String content",
"Level":1,
}],
[{
"TreeName":"String content",
"Level":2,
}],
[{
"TreeName":"String content",
"Level":2,
}],
[{
"TreeName":"String content",
"Level":1,
}],
[{
"TreeName":"String content",
"Level":2,
}],
[{
"TreeName":"String content",
"Level":3,
}],
[{
"TreeName":"String content",
"Level":1,
}]
If level 0 then its main node and level 1 becomes parent node and level 2 becomes that parents child node and level 3 becomes that childs child node and so forth.
I have tried many examples and doesnt work, the only thing is that I thought was to do a lot of if statements but i need a shorter and more efficient way.
You can use jsTree.jsTree is jquery plugin, that provides interactive trees. It is absolutely free, open source and distributed under the MIT license. jsTree is easily extendable, themable and configurable, it supports HTML & JSON data sources and AJAX loading. You can find more detail on https://www.jstree.com/
Here is the code
$('#jstree_demo').jstree({
"core" : {
"animation" : 0,
"check_callback" : true,
"themes" : { "stripes" : true },
'data' : {
'url' : function (node) {
return node.id === '#' ?
'ajax_demo_roots.json' : 'ajax_demo_children.json';
},
'data' : function (node) {
return { 'id' : node.id };
}
}
},
"types" : {
"#" : {
"max_children" : 1,
"max_depth" : 4,
"valid_children" : ["root"]
},
"root" : {
"icon" : "/static/3.3.2/assets/images/tree_icon.png",
"valid_children" : ["default"]
},
"default" : {
"valid_children" : ["default","file"]
},
"file" : {
"icon" : "glyphicon glyphicon-file",
"valid_children" : []
}
},
"plugins" : [
"contextmenu", "dnd", "search",
"state", "types", "wholerow"
]
});
Also you can find working demo on https://www.jstree.com/demo/
And here is the format of data to use jstree https://www.jstree.com/docs/json/

find in mongoDB documents with filled nested array and build new result object

I have some document with this structure - the category field can also be empty
{
"_id" : "1",
"category" : [
{ "target" : "element 1" },
{ "target" : "element 2" }
]
},
{
"_id" : "2",
"category" : [
{ }
]
},
{
"_id" : "3",
"category" : [
{ "target" : "element 1" },
{ "target" : "element 2" }
]
},
What I need is a result like
{ id: 1, element: "element 1" },
{ id: 1, element: "element 2" },
{ id: 3, element: "element 1" },
{ id: 3, element: "element 2" }
That means first I have to check for all documents which have target elements:
var result = db.collection.find({}, { 'category.target': 1})
1) But this doesn't work, as I still get the empty doc (2).
2) Second I need to get a new result element for each element in the target-array. I think aggregate isn't the correct way as there has to be new objects for each element. And map is only to nave the fields.
So I think I have to iterate over the results and build a new object, correct?
result.forEach(function($res){
// do a new foreach for every element in target-array?
newResult.push({ id: res._id, element: res.element });
});
You can do this using aggregate which, unlike find, allows you to reshape documents.
db.test.aggregate([
// Duplicate each doc, once per category element
{$unwind: '$category'},
// Reshape the documents to create the element field
{$project: {element: '$category.target'}},
// Only include docs with an element
{$match: {element: {$exists: true}}}
])
Result:
"result" : [
{
"_id" : "1",
"element" : "element 1"
},
{
"_id" : "1",
"element" : "element 2"
},
{
"_id" : "3",
"element" : "element 1"
},
{
"_id" : "3",
"element" : "element 2"
}
]

Backbone nested collection

I have an app in backbone that retrieve data from a server. This data are hotels and foreach hotel I have more rooms. I have divided hotel into a json and rooms inside another json like this:
hotel.json
[
{
"id": "1",
"name": "Hotel1"
},
{
"id": "2",
"name": "Hotel2"
},
{
"id": "3",
"name": "Hotel3"
}
]
rooms.json
[
{
"id" : "r1",
"hotel_id" : "1",
"name" : "Singola",
"level" : "1"
},
{
"id" : "r1_1",
"hotel_id" : "1",
"name" : "Doppia",
"level" : "2"
},
{
"id" : "r1_3",
"hotel_id" : "1",
"name" : "Doppia Uso singol",
"level" : "1"
},
{
"id" : "r2",
"hotel_id" : "2",
"name" : "Singola",
"level" : "1"
},
{
"id" : "r2_1",
"hotel_id" : "2",
"name" : "Tripla",
"level" : "1"
}
]
I wanna take each hotel and combine with its rooms (external key into rooms.json hotel_id) and print the combination of the rooms: foreach level combine different rooms.
One room of level 1, one room of level 2 and one room of level 3.
Maximum of level is 3 but I can have only one level or only two level.
If I have 3 level I don't want combination of level 1 and level 2 without level 3.
Something like this
Room "Single", "level" : "1" , "hotel_id" : "1"
Room "Double", "level" : "2" , , "hotel_id" : "1"
Room "Triple", "level" : "3" , , "hotel_id" : "1"
Room "Double for single", "level" : "1" , "hotel_id" : "1"
Room "Double", "level" : "2" , , "hotel_id" : "1"
Room "Triple", "level" : "3" , , "hotel_id" : "1"
The constructor of this rooms I think is to put into renderRooms into my app.
This is my app:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model: Room,
url: "includes/rooms.json"
});
var Hotel = Backbone.Model.extend({
defaults: function() {
return {
"id": "1",
"name": "Hotel1",
"rooms": []
}
}
});
var HotelCollection = Backbone.Collection.extend({
model: Hotel,
url: "includes/test-data.json",
initialize: function() {
console.log("Collection Hotel initialize");
}
});
var HotelView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function() {
this.collection = new HotelCollection();
this.collection.bind('sync', this.render, this);
this.collection.fetch();
},
render: function() {
console.log('Data hotel is fetched');
this.bindRoomToHotel();
var element = this.$el;
element.html('');
},
bindRoomToHotel: function() {
allRooms = new Rooms();
allRooms.on("sync", this.renderRooms, this)
allRooms.fetch();
},
renderRooms: function() {
$(this.el).html(this.template({ hotels: this.collection.models }));
}
});
var hotelView = new HotelView({
el: $("#hotel")
});
How can I create this room combination and print it?
Is there a good way or there is something better?
Here is how you can structure the Collections:
HotelModel = Backbone.Model.extend({
initialize: function() {
// because initialize is called after parse
_.defaults(this, {
rooms: new RoomCollection
});
},
parse: function(response) {
if (_.has(response, "rooms")) {
this.rooms = new RoomCollection(response.rooms, {
parse: true
});
delete response.rooms;
}
return response;
},
toJSON: function() {
var json = _.clone(this.attributes);
json.rooms = this.rooms.toJSON();
return json;
}
});
RoomModel = Backbone.Model.extend({
});
HotelCollection = Backbone.Collection.extend({
model: HotelModel
});
RoomCollection = Backbone.Collection.extend({
model: RoomModel
});
Then you can do something like this:
var hotels = new HotelCollection();
hotels.reset([{
id: 1,
name: 'Hotel California',
rooms: [{
id: 1,
name: 'Super Deluxe'
}]
}], {
parse: true // tell the collection to parse the data
});
// retrieve a room from a hotel
hotels.get(1).rooms.get(1);
// add a room to the hotel
hotels.get(1).rooms.add({id:2, name:'Another Room'});

Creating relationships between items in a Knockout.js model

jsFiddle: http://jsfiddle.net/brandondurham/g3exx/
How can I create relationships between various observableArrays in my model? For instance, in my model I have a cartItems array, and each item in that array has a nested itemFreebies array as well as an itemType property. Customers only get free items when they have a subscription in their cart ("itemType" : "subscription") and, as such, when that subscription is removed I need to remove all other cart items' freebies, preferably with a nice fadeOut animation.
What is the best way to create these types of conditional relationships?
This is the object I'm using in my model:
{
"cartItems" : [
{
"itemName" : "Product 1",
"itemDesc" : "Product 1 description",
"itemType" : "subscription",
"itemPrice" : 299,
"itemFreebies" : false
}, {
"itemName" : "Product 2",
"itemDesc" : "Product 2 description",
"itemType" : "desktop",
"itemPrice" : 4499,
"itemFreebies" : [{
"freebieName" : "Product 2 freebie",
"freebieDesc" : "Product 2 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 3",
"itemDesc" : "Product 3 description",
"itemType" : "desktop",
"itemPrice" : 8999,
"itemFreebies" : [{
"freebieName" : "Product 3 freebie",
"freebieDesc" : "Product 3 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 4",
"itemDesc" : "Product 4 description",
"itemType" : "desktop",
"itemPrice" : 99,
"itemFreebies" : [{
"freebieName" : "Product 4 freebie",
"freebieDesc" : "Product 4 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 5",
"itemDesc" : "Product 5 description",
"itemType" : "webfont",
"itemPrice" : 49,
"itemFreebies" : false
}
]
}
I would start with something like this:
$(function () {
​var CartViewModel = {
var self = this;
self.cartItems = ko.observableArray([]);
self.eligibleForFreebies = ko.computed(function() {
return ko.utils.arrayFirst(self.cartItems(), function(cartItem) {
// I forgot the () after itemType in the original post
return (cartItem.itemType() === 'subscription');
});
// Note: ko.utils.arrayFirst will either return the item in
// question, or it will return undefined or null…
// I forget which, but either will result in
// eligibleForFreebies evaluating to false
});
};
var Product = function() {
var self = this;
self.itemName = ko.observable();
self.itemDesc = ko.observable();
self.itemType = ko.observable();
self.itemPrice = ko.observable();
self.itemFreebies = ko.observableArray([]);
};
var Freebie = function() {
var self = this;
self.freebieName = ko.observable();
self.freebieDesc = ko.observable();
self.freebieOriginalPrice = ko.observable();
}
ko.applyBindings(new CartViewModel());
// load data
});
​
Load Products into the cartItems observableArray in the CartViewModel.
The dependent observable (ko.computed) value eligibleForFreebies will determine whether or not the Freebies should be allowed.
It's likely that you wouldn't even need to remove the freebies from the Products when the cart is not eligible for them – simply check eligibleForFreebies and include or exclude the freebies from the display, invoice, etc. (This might save you the headache of retrieving freebies after the user adds the subscription, but I suppose that depends on your scenario.)
Hope this helps to get you started on this one, but let me know if you have any questions.
UPDATE: I forked your fiddle and reworked your code a bit... well, I mostly moved it around, but I did add some functionality.
Notice that if you delete the subscription item from the cart, all the freebies disappear from the cart display--but I didn't delete them from the objects!
If one adds a method for re-adding a subscription item to the cart, the freebies would reappear.
Please have a look when you have a chance, and let me know if you'd like me to explain anything.

Categories