SnailApp---数据流的控制(一)

来源:互联网 发布:淘宝订单自动关闭 编辑:程序博客网 时间:2024/06/13 00:42

SnailApp—数据流的控制(一)

一、简介

搭建Flux框架及其辅助框架

二、技术应用

1. Flux

  • 插件安装:npm install flux –save
  • homepage:https://github.com/facebook/flux
  • 作用:数据流控制主体框架

2. Events

  • 插件安装:npm install events –save
  • homepage:https://github.com/Gozala/events#readm
  • 作用:数据变化监听事件

三、搭建框架

1. 创建DispatcherUtils.js文件

路径:/components/dispatcher/DispatcherUtils.js

  • 更多内容请跳转
  • http://blog.csdn.net/fsf_snail/article/details/71080934
  • http://blog.csdn.net/fsf_snail/article/details/71080950
'use strict'import { Dispatcher } from 'flux'const flux = new Dispatcher()export function register(callback) {    return flux.register(callback)}export function waitFor(ids) {    return flux.waitFor(ids)}/** * Dispatches a single action. */export function dispatch(type, action = {}) {    if(!type) {        throw new Error('You forgot to specify type.')    }    if(process.env.NODE_ENV !== 'production') {        if(action.error) {            console.error(type, action)        } else {            console.log({ type, ...action })        }    }    flux.dispatch({ type, ...action })}/** * Dispatches three actions for an async operation represented by promise. */export function dispatchAsync(promise, types, action = {}) {    const { request, success, failure } = types;    dispatch(request, action);    promise.then(        response => dispatch(success, { ...action, response }),        error => dispatch(failure, { ...action, error })    )}

2. 创建StoreUtils.js文件

路径:/components/utils/StoreUtils.js

'user strict'import { EventEmitter } from 'events'import { each, isFunction } from 'underscore'const CHANGE_EVENT = 'change'export function createStore(spec) {    const emitter = new EventEmitter()    // 默认最多可加入10个监听事件,设置成Infinity或者0表示不限制个数    emitter.setMaxListeners(0)    // Merging objects    const store = Object.assign({        emitEvent(event) {            emitter.emit(event)        },        addEventListener(event, callback) {            emitter.on(event, callback)        },        removeEventListener(){            emitter.removeListener(event, callback)        },        emitChange() {            emitter.emit(CHANGE_EVENT)        },        addChangeListener(callback) {            emitter.on(CHANGE_EVENT, callback)        },        removeChangeListener() {            emitter.removeListener(CHANGE_EVENT, callback)        }    }, spec)    each(store, (val, key) => {        if(isFunction(val)) {            store[key] = store[key].bind(store)        }    })    return store}
原创粉丝点击