Created
March 2, 2016 03:34
-
-
Save gautamborad/601c9b720c2f6fce63a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {observable, autorun} from 'mobx'; | |
import axios from 'axios'; | |
import Post from '../models/postModel'; // TODO!! | |
export default class BaseStore { | |
@observable models = []; | |
@observable isLoading = true; | |
constructor(type, url) { | |
this.type = type; | |
this.url = url; | |
} | |
/** | |
* Fetches all posts's from the server | |
*/ | |
loadModels() { | |
axios.get(this.url).then(fetchedModels => { | |
fetchedModels.forEach(json => this.updateModelFromServer(json)); | |
}); | |
} | |
/** | |
* Update a post with information from the server. Guarantees a post | |
* only exists once. Might either construct a new post, update an existing one, | |
* or remove an post if it has been deleted on the server. | |
*/ | |
updateModelFromServer(json) { | |
var model = this.models.find(model => model.id === json.id); | |
if (!model) { | |
model = new Post(this, json.id); // TODO How to get the type of Class here?? | |
this.models.push(model); | |
} | |
if (json.isDeleted) { | |
this.removeModel(model); | |
} else { | |
post.updateFromJson(json); | |
} | |
} | |
/** | |
* Creates a fresh post on the client and server | |
*/ | |
createModel() { | |
var model = new Post(this); // TODO How to get the type of Class here?? | |
this.models.push(model); | |
return model; | |
} | |
/** | |
* A post was somehow deleted, clean it from the client memory | |
*/ | |
removeModel(model) { | |
this.models.splice(this.models.indexOf(model), 1); | |
model.dispose(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {observable, autorun} from 'mobx'; | |
import BaseStore from '../stores/BaseStore' | |
export class PostStore extends BaseStore{ | |
constructor() { | |
super('post','/posts/'); | |
super.loadModels(); | |
} | |
} | |
let singleton = new PostStore() | |
export default singleton |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment