var data = Observable();
var total = 0;
function addItem(isbn, name, price, quantity)
{
var tempData = new Item(isbn, name, price, quantity);
data.add(tempData);
totalPrice(price,quantity);
};
totalPrice(p,q){
//console.log(p);
//console.log(q);
//don't know what goes here. I want to return total ( declared above). total = price * quantity
}
But in your case I suppose addItem is called from a UX event so I’m curious about what is receiving the Item instance. Could you provide where you call the addItem method?
I can’t totally get what isn’t working as intended. Could you post a fully working example that demonstrates your case? It seems like there’s some code missing.
Here’s my minimal code production. I want to access data observable and calculate total cost for book. Also total cost change based on item added by users.
var Observable = require('FuseJS/Observable');
var data = Observable();
var total = 0;
function Item(isbn, name, price, quantity){
this.isbn = isbn;
this.name = name;
this.price = price;
this.quantity = quantity;
}
function addItem(isbn, name, price, quantity)
{
var tempData = new Item(isbn, name, price, quantity);
data.add(tempData);
};
function calculatePrice()
{
//how to calculate total price??
//lost here
//need to calculate total price whenever user add item
//Total price = price * quantitiy;
};
function addButton()
{ //summary
//whenever user want to purchase the book and clicked on addButton. This
will get triggered.
//exclude product image
//doesn't calculate total price
addItem(14002,"Tom books",5.99,2);
addItem(15002,"books",4.99,3);
}
module.exports = {
addItem:addItem,
calculatePrice:calculatePrice,
addButton:addButton,
total:total,
data:data
};
Ok, I have a workaround. First I change total to observable because it needs to be updated in the UI, and calculate the total using every element in the data list.
var Observable = require('FuseJS/Observable');
var data = Observable();
var total = Observable(0);
function Item(isbn, name, price, quantity){
this.isbn = isbn;
this.name = name;
this.price = price;
this.quantity = quantity;
this.getTotal = function() {
return quantity * price;
}
}
function addItem(isbn, name, price, quantity)
{
var tempData = new Item(isbn, name, price, quantity);
data.add(tempData);
};
function calculatePrice()
{
total.value = 0;
data.forEach(function(b) {
total.value += b.getTotal();
})
}
function addButton()
{ //summary
//whenever user want to purchase the book and clicked on addButton. This will get triggered.
//exclude product image
//doesn't calculate total price
addItem(14002,"Tom books",5.99,2);
addItem(15002,"books",4.99,3);
}
module.exports = {
addItem:addItem,
calculatePrice:calculatePrice,
addButton:addButton,
total:total,
data:data
};
@Tom: you can’t require() viewmodels. This has been a common mistake and has already been explained before. Please start here and follow the links for details.