I'm working on choices gathering app and I got stuck at working with objects: User have list of cards, each card have list of choices, each choice have id and price. I want to gather user selection at each card and than count final price. I don't know exact names of cards, they will be generated. I know only the class of selected card or card list count.
data collection:
var datacollection = {
shape: {
itemId: 1,
price: 10
},
countmoney: function () {
var cash = 0;
$.each(this, function (id, item) {
if (typeof (item) != 'function') {
cash += item.price;
}
});
return cash + ' $';
}
};
data gathered from .click(function() {
var cardClass = 'color';
var choiceId = 2;
var choicePrice = 50;
I can insert new data, but ONLY if I know name of the card
datacollection.color = {
itemId: choiceId,
price: choicePrice
};
But what if I don't know the possible name of card? Using bracket notation should be the way to go.. but it doesn't work.
cardClassTwo = 'material';
datacollection[cardClassTwo]['itemId'] = choiceId;
datacollection[cardClassTwo]['price'] = choicePrice;
// Uncaught TypeError: Cannot set property 'itemId' of undefined
console.log(datacollection.countmoney());
Code to play with: http://jsfiddle.net/F5pt6/
$.each(this, function (id, item) {be$.each(datacollection, function (id, item) {asthisin that scope, would be the equivalent ofwindowdatacollection.countmoney()is calling it as a member of the object.datacollection[cardClass] = {