Created
February 21, 2015 21:03
-
-
Save jacobthemyth/2ab30c45d75f54ae3681 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Item = Backbone.Model.extend({ | |
defaults: { | |
name: '', | |
price: '' | |
} | |
}); | |
var ItemCollection = Backbone.Collection.extend({ | |
model: Item, | |
url: "https://api.parse.com/1/classes/Item", | |
parse: function(response){ | |
return response.results; | |
} | |
}); | |
var Order = Backbone.Model.extend({ | |
// define defaults as a function, otherwise the items array will be shared | |
// among all orders. See http://backbonejs.org/#Model-defaults | |
defaults: function(attributes){ | |
attributes = attributes || {}; | |
return _.defaults(attributes, { | |
items: [] | |
}); | |
}, | |
addItem: function(item){ | |
// 1. use item.toJSON since we need to turn a model into an object that | |
// looks like {name: "Cool Food", price: 100} | |
// 2. use set + concat because, if you were to just modify items in place | |
// (e.g. using .push) it wouldn't fire a change event. .concat takes an | |
// array and returns a new array of the two arrays combined, so it will | |
// fire a change event. | |
this.set('items', this.get('items').concat([item.toJSON()])); | |
}, | |
totalPrice: function(){ | |
return this.get('items').reduce(function(acum, item) { | |
return acum + item.price; | |
}, 0); | |
} | |
}); | |
var OrderCollection = Backbone.Model.extend({ | |
model: Order, | |
url: "https://api.parse.com/1/classes/Order", | |
parse: function(response){ | |
return response.results; | |
} | |
}); | |
var items = new ItemCollection([{name: "Cool Food", price: 10.5}]); | |
var order = new Order(); | |
order.addItem(items.at(0)) | |
console.log(order.totalPrice()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment