Creating relationships between items in a Knockout.js model - javascript

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.

Related

Loop through array of objects and check conditions

I have an array of object like this
list = [
{
"label" : "whatever",
"value" : "value 1"
},
{
"label" : "whatever",
"value" : "value 2"
},
{
"label" : "Required scenario only",
"value" : "value 3"
},
{
"label" : "whatever",
"value" : "value 4"
},
]
I am running for a loop with conditions, I want to execute some piece of code only for one scenario called 'Required scenario only' for the rest of all scenarios run different code for only one time, it should not execute 3 times as per loop executes
for(i=0; i< list.length; i++) {
if(list[i].label === 'Required scenario only' ) {
//execute some code
} else {
// execute code for 1 time for rest of the labels i.e for all 'whatever' scenarios
}
}
How should I do it?
If you're merely checking for the existence of an object with label = "Required scenario only" then I would use Array.some():
list = [{
label: "whatever",
value: "value 1"
},
{
label: "whatever",
value: "value 2"
},
{
label: "Required scenario only",
value: "value 3"
},
{
label: "whatever",
value: "value 2"
},
]
if (list.some(l => (l.label == "Required scenario only"))) {doSomething();}
else {doSomethingElse();}
function doSomething() {console.log("Do Something");}
function doSomethingElse() {console.log("Do Something Else");}

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()

Query in firebase usining angular 4 and angularFire 2

I try to query a list from 5000 products that have property = 110571 is not do anything
I use angularfire 2 but for the last 5 hours, I don't get anything help me.
What is the best way to do that?
This is the object in Firebase database
"products" : {
1753: {
"name" : "sprite",
"custom_id" : 534253,
"description" : "some small description"
},
1754: {
"name" : "coca cola",
"custom_id" : 110571, <---- i want to find if this node from 5000 products exist in database and if exist i want to return true
"description" : "some small description"
},
1755: {
"name" : "fanta",
"custom_id" : dsgfsdfds,
"description" : "some small description"
},
}
This is the function that I use
x = 1754;
check_if_product_code_exist(x) {
console.log(x);
this.searchSubject.next(x);
// this.products = this.db.list('/products') as FirebaseListObservable<Product[]>;
this.products = this.db.list('/products', { query: {
orderByChild: 'custom_id',
equalTo: this.searchSubject,
limitToFirst: 1
}} ) as FirebaseListObservable<Product[]>;
console.log(this.products);
return this.products;
}

Dojo Tree based on ItemFileReadStore and parent-based model

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(...);

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'});

Categories