salix/client/core/src/components/model-proxy/model-proxy.js

136 lines
3.0 KiB
JavaScript
Raw Normal View History

import ngModule from '../../module';
export default class ModelProxy {
constructor() {
this._data = [];
this.resetChanges();
}
get orgData() {
return this._orgData;
}
set orgData(value) {
this._orgData = value;
// this._data.splice(0, this._data.length);
if (this.Row) {
this._data = [];
for (let i = 0; i < value.length; i++) {
let row = new this.Row(value[i], i);
this._data.push(row);
}
} else
this._data = value;
this.resetChanges();
}
get data() {
return this._data;
}
set data(value) {}
get fields() {
return this._fields;
}
set fields(value) {
this._fields = value;
let Row = function(data, index) {
this.$data = data;
this.$index = index;
this.$oldData = null;
this.$isNew = false;
};
for (let prop of value) {
Object.defineProperty(Row.prototype, prop, {
enumerable: true,
configurable: false,
set: function(value) {
if (!this.$isNew) {
if (!this.$oldData)
this.$oldData = {};
if (!this.$oldData[prop])
this.$oldData[prop] = this.$data[prop];
}
this.$data[prop] = value;
},
get: function() {
return this.$data[prop];
}
});
}
this.Row = Row;
}
remove(index) {
let data = this._data;
let item;
[item] = data.splice(index, 1);
for (let i = index; i < data.length; i++)
data[i].$index = i;
if (!item.$isNew)
this.removed.push(item);
}
insert(data) {
data = Object.assign(data || {}, this.link);
let newRow = new this.Row(data, this._data.length);
newRow.$isNew = true;
return this._data.push(newRow);
}
resetChanges() {
this.removed = [];
for (let row of this._data) {
row.$oldData = null;
row.$isNew = false;
}
}
undoChanges() {
let data = this._data;
for (let i = 0; i < data.length; i++) {
let row = data[i];
if (row.$oldData)
Object.assign(row.$data, row.$oldData);
if (row.$isNew)
data.splice(i--, 1);
}
for (let row of this.removed)
data.splice(row.$index, 0, row);
this.resetChanges();
}
dataChanged() {
if (this.onDataChange)
this.onDataChange();
}
}
ngModule.component('vnModelProxy', {
controller: ModelProxy,
bindings: {
orgData: '<?',
data: '=?',
fields: '<?',
link: '<?',
onDataChange: '&?'
}
});