<!DOCTYPE html>
<html>
<head>
<title>Ember Collection Example</title>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.4.0/ember.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ember-data.js/2.4.0/ember-data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.4.0/ember-template-compiler.js"></script>
</head>
<body>
<script src="script.js"></script>
<script type="text/x-handlebars">
<h1>Ember Collection Example</h1> {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<p>
<label>
Name {{input value=model.name}}
</label>
</p>
<ul>
{{#each model.editableAddress as |line index|}}
<li>
{{input value=line.value}}
<span {{action "removeLine" index}} style="cursor: pointer;">[-]</span>
</li>
{{/each}}
<li>
<span {{action "addLine"}} style="cursor: pointer;">[+]</span>
</li>
</ul>
<button type="button" {{action "saveAddress"}}>Save Address</button>
</script>
</body>
</html>
var App = Ember.Application.create({});
App.ShippingAddress = DS.Model.extend({
name: DS.attr('string'),
address: DS.attr({
defaultValue: function () {
return [];
}
}),
editableAddress: Ember.computed('address', function () {
var address = this.get('address') || [];
return address.map(function (line) {
return { value: line };
});
})
});
App.IndexRoute = Ember.Route.extend({
model() {
return this.store.createRecord('shipping_address', {
name: '',
address: ['']
});
}
});
App.IndexController = Ember.Controller.extend({
actions: {
addLine() {
var editableAddress = this.get('model.editableAddress');
editableAddress.pushObject({ value: '' });
},
removeLine(index) {
var editableAddress = this.get('model.editableAddress');
editableAddress.removeAt(index);
},
saveAddress() {
updateShippingAddress.call(this);
var msg = `Name: ${this.get('model.name')}\n`;
this.get('model.address').forEach(function (line) {
msg += `${line}\n`
});
console.log(msg);
}
}
});
function updateShippingAddress() {
var editableAddress = this.get('model.editableAddress');
var address = [];
editableAddress.forEach(function (line) {
if (line.value && line.value.trim().length) {
address.push(line.value.trim());
}
});
this.get('model').set('address', address);
}
console.log("Application is loaded.");
# Ember Collection Example