From e9ae541d0e6ff2fd7c32580f2b62adc3266af5d2 Mon Sep 17 00:00:00 2001 From: Chow Hui Ling Date: Sun, 3 Jan 2016 22:35:54 +0800 Subject: [PATCH] add alt to TODO list app. --- app/components/App.jsx | 52 ++++++++++++++++------------------------- app/stores/NoteStore.js | 4 ++-- 2 files changed, 22 insertions(+), 34 deletions(-) diff --git a/app/components/App.jsx b/app/components/App.jsx index 289c722..d0c18a1 100644 --- a/app/components/App.jsx +++ b/app/components/App.jsx @@ -1,30 +1,30 @@ import React from 'react'; import Notes from './Notes.jsx'; +import NoteActions from '../actions/NoteActions'; +import NoteStore from '../stores/NoteStore'; export default class App extends React.Component { constructor(props) { super(props); - this.state = { - notes: [ - { - id: uuid.v4(), - task: 'Learn webpack' - }, - { - id: uuid.v4(), - task: 'Learn react' - }, - { - id: uuid.v4(), - task: 'go sleep' - } - ] - }; + this.state = NoteStore.getState(); //bind the "this" context to the function so "this" works in the function this.addNote = this.addNote.bind(this); } + componentDidMount() { + NoteStore.listen(this.storeChanged); + } + + componentWillUnmount() { + NoteStore.unlisten(this.storeChanged); + } + + storeChanged = (state) => { + //must initialize the state so that it points to the right context. + this.setState(state); + } + render() { const notes = this.state.notes; return ( @@ -36,28 +36,16 @@ export default class App extends React.Component { } //addNote = () => { //uncomment this line and remove the binding event above to use the new syntax. addNote() { - this.setState({ - notes: this.state.notes.concat([{ - id: uuid.v4(), - task: 'New task' - }]) - }); + NoteActions.create({task: 'New task'}); + console.log('add note'); } editNote = (id, task) => { - const notes = this.state.notes.map((note) => { - if (note.id === id) { - note.task = task; - } + NoteActions.update({id, task}); - return note; - }); - this.setState({notes}); } deleteNote = (id) => { + NoteActions.delete(id); console.log("deleting node:",id); - this.setState({ - notes: this.state.notes.filter((note) => note.id !== id) - }); } } diff --git a/app/stores/NoteStore.js b/app/stores/NoteStore.js index 595a7f4..347882b 100644 --- a/app/stores/NoteStore.js +++ b/app/stores/NoteStore.js @@ -6,7 +6,7 @@ class NoteStore { constructor() { //use bindActions to map each action in NodeActions to a method by name. this.bindActions(NoteActions); - this.notes = []; + this.notes = [{id: uuid.v4(), task:'test'}]; } create(note) { @@ -32,7 +32,7 @@ class NoteStore { delete(noteId) { this.setState({ notes: this.notes.filter((note) => note.id !== nodeId) - + }); } }