Created
July 23, 2014 15:06
-
-
Save kamilogorek/df66f02c452f67170062 to your computer and use it in GitHub Desktop.
This file contains 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 Collection = require("ampersand-rest-collection"); | |
var Model = require("ampersand-model"); | |
var Product = Model.extend({ | |
props: { | |
name: 'string', | |
price: 'integer' | |
} | |
}); | |
var Products = Collection.extend({ | |
model: Product, | |
initialize: function () { | |
this.listenTo(this, 'change:price', this.notifyPriceChange); | |
}, | |
notifyPriceChange: function () { | |
this.trigger('priceChange', this.calculateTotal()); | |
}, | |
calculateTotal: function () { | |
return this.pluck('price').reduce(function (a, b) { | |
return a + b; | |
}); | |
} | |
}); | |
var products = new Products([{ | |
name: 'foo', | |
price: 10 | |
}, { | |
name: 'bar', | |
price: 15 | |
}, { | |
name: 'baz', | |
price: 20 | |
}]); | |
var Foo = Collection.extend({ | |
initialize: function () { | |
this.listenTo(products, 'priceChange', this.logTotal); | |
}, | |
logTotal: function (total) { | |
console.log('Hey, prices changed! New total price is: ' + total); | |
} | |
}); | |
var foo = new Foo(); | |
setTimeout(function () { | |
products.first().set('price', 12); | |
}, 1000); | |
setTimeout(function () { | |
products.first().set('price', 18); | |
}, 2000); | |
setTimeout(function () { | |
products.first().set('price', 22); | |
}, 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment