sameshit with knockout.js
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<table>
<thead>
<tr>
<th>shit1</th>
<th>shit2</th>
<th>Сумма</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr>
<td><input type="text" data-bind="value: shit1"></td>
<td><input type="text" data-bind="value: shit2"></td>
<td data-bind="text: sum()"></td>
<td>
<button data-bind="click: $root.deleteRow">X</button>
</td>
</tr>
</tbody>
</table>
<button data-bind="click: addRow">добавить строку</button>
JavaScript
ko.extenders.numeric = function(target) {
var result = ko.pureComputed({
read: target,
write: function(newValue) {
newValue = parseInt(newValue) || 0;
target(newValue);
}
}).extend({notify: 'always'});
result(target());
return result;
};
function Row(shit1, shit2) {
var self = this;
self.shit1 = ko.observable(shit1).extend({numeric: ''});
self.shit2 = ko.observable(shit2).extend({numeric: ''});
self.sum = ko.computed(function() {
var result = self.shit1() + self.shit2();
return result || 0;
});
}
function App() {
var self = this;
self.rows = ko.observableArray([
new Row(1, 2), new Row(3, 4)
]);
self.addRow = function() {
self.rows.push(new Row(0, 0));
}
self.deleteRow = function(row) {
self.rows.remove(row)
}
}
ko.applyBindings(new App());