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:
Load Products into the cartItems observableArray in the CartViewModel.
The dependent observable (ko.computed) value
eligibleForFreebieswill 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
eligibleForFreebiesand 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.