mirror of
https://github.com/flarum/framework.git
synced 2025-05-23 07:09:57 +08:00
Replace Ember app with Mithril app
This commit is contained in:
88
js/lib/model.js
Normal file
88
js/lib/model.js
Normal file
@ -0,0 +1,88 @@
|
||||
export default class Model {
|
||||
constructor(data, store) {
|
||||
this.data = m.prop(data || {});
|
||||
this.freshness = new Date();
|
||||
this.exists = false;
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
pushData(newData) {
|
||||
var data = this.data();
|
||||
|
||||
for (var i in newData) {
|
||||
if (i === 'links') {
|
||||
data[i] = data[i] || {};
|
||||
for (var j in newData[i]) {
|
||||
if (newData[i][j] instanceof Model) {
|
||||
newData[i][j] = {linkage: {type: newData[i][j].data().type, id: newData[i][j].data().id}};
|
||||
}
|
||||
data[i][j] = newData[i][j];
|
||||
}
|
||||
} else {
|
||||
data[i] = newData[i];
|
||||
}
|
||||
}
|
||||
|
||||
this.freshness = new Date();
|
||||
}
|
||||
|
||||
save(data) {
|
||||
if (data.links) {
|
||||
for (var i in data.links) {
|
||||
var model = data.links[i];
|
||||
data.links[i] = {linkage: {type: model.data().type, id: model.data().id}};
|
||||
}
|
||||
}
|
||||
|
||||
this.pushData(data);
|
||||
|
||||
return m.request({
|
||||
method: this.exists ? 'PUT' : 'POST',
|
||||
url: app.config.apiURL+'/'+this.data().type+(this.exists ? '/'+this.data().id : ''),
|
||||
data: {data},
|
||||
background: true,
|
||||
config: app.session.authorize.bind(app.session)
|
||||
}).then(payload => {
|
||||
this.store.data[payload.data.type][payload.data.id] = this;
|
||||
return this.store.pushPayload(payload);
|
||||
});
|
||||
}
|
||||
|
||||
delete() {
|
||||
if (!this.exists) { return; }
|
||||
|
||||
return m.request({
|
||||
method: 'DELETE',
|
||||
url: app.config.apiURL+'/'+this.data().type+'/'+this.data().id,
|
||||
background: true,
|
||||
config: app.session.authorize.bind(app.session)
|
||||
}).then(() => this.exists = false);
|
||||
}
|
||||
|
||||
static prop(name, transform) {
|
||||
return function() {
|
||||
var data = this.data()[name];
|
||||
return transform ? transform(data) : data
|
||||
}
|
||||
}
|
||||
|
||||
static one(name) {
|
||||
return function() {
|
||||
var link = this.data().links[name];
|
||||
return link && app.store.getById(link.linkage.type, link.linkage.id)
|
||||
}
|
||||
}
|
||||
|
||||
static many(name) {
|
||||
return function() {
|
||||
var link = this.data().links[name];
|
||||
return link && link.linkage.map(function(link) {
|
||||
return app.store.getById(link.type, link.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static date(data) {
|
||||
return data ? new Date(data) : null;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user