EmberJS template
by savid
HTML
<script src="https://github.com/downloads/emberjs/ember.js/ember-0.9.8.1.js"></script>
<script type="text/x-handlebars">
<h1>Test</h1>
{{#collection contentBinding="App.productsController.selectedProducts" tagName="ul"}}
<li>{{ content.name }}: {{view Ember.TextField valueBinding="content.price"}}</li>
{{/collection}}
<p><strong>Total: {{ App.calculator.total }}</strong></p>
</script>
CSS
li {padding: 5px;}
input {padding-left: 5px;}
strong {font-weight: bold}
p {margin-top: 1em}
JavaScript
App = Ember.Application.create();
App.Product = Ember.Object.extend({
name: null,
price: 0,
selected: false
});
App.productsController = Ember.Object.create({
init: function() {
this.set('products', [
App.Product.create({name: 'Foo', selected: true, brand: 'X'}),
App.Product.create({name: 'Bar', selected: true, brand: 'X'}),
App.Product.create({name: 'Baz', selected: true, brand: 'X'}),
App.Product.create({name: 'Qux', selected: false, brand: 'Y'}),
App.Product.create({name: 'Qux', selected: true, brand: 'Y'}),
]);
},
products: [],
brandProducts: function() {
return this.get('products').filterProperty('brand', 'X');
}.property('products', '[email protected]').cacheable(),
selectedProducts: function() {
return this.get('brandProducts').filterProperty('selected', true);
}.property('brandProducts', '[email protected]').cacheable()
});
App.calculator = Ember.Object.create({
total: function(){
console.log('total called');
var t = 0;
var products = App.productsController.get('selectedProducts');
products.forEach(function(product) {
var price = parseFloat(product.get('price'));
if (!isNaN(price)) t += price;
});
return t;
}.property('[email protected]').cacheable()
});