委托 接口 事件 多态

2016-11-10  本文已影响0人  楚怀哲

委托 接口

声明:

/**
 * Created by kenny on 16/3/28.
 */
'use strict';
import React, {
  Component,
  PropTypes
} from 'react';
import {
  AppRegistry,
  View,
  Navigator,
  StyleSheet,
  StatusBar,
  DeviceEventEmitter,
} from 'react-native';

import SplashPage from './pages/SplashPage';
import { naviGoBack } from './utils/CommonUtil';
import LoadingView from './components/LoadingView';
import {STYLESBASE} from './constants/StylesBase';
import MainEnterPage from './pages/MainEnterPage'

let tempNavigator;
let initLoadingState={
  isShow:false,
  AcIndicShow:true,
  text:'数据加载中',
};

class HL_LY_APP_RN extends Component {

  constructor(props){
    super(props);
    this.state = {
      LoadingState: initLoadingState,
    }; 
    this.init = this.init.bind(this);
    this.renderScene = this.renderScene.bind(this);
    this.goBack = this.goBack.bind(this);
  }

  init() {
  }

  componentWillMount(){
    AppController.LoadingState = (LoadingStateData) => {
      this.setState({
        LoadingState: LoadingStateData
      });
    }
  }

  componentDidMount() {
  }

  componentWillUnmount() {
  }

  goBack() {
    return naviGoBack(tempNavigator);
  }

  configureScene() {
      var conf = Navigator.SceneConfigs.HorizontalSwipeJump;
      conf.gestures = null;
      return conf;
  }

  renderScene(route, navigator) {
    let Component = route.component;
    return <Component {...route.params} navigator={navigator} />
  }

  render() {
    var defaultName = 'Splash';
    var defaultComponent = MainEnterPage;
    var defaultSceneConfig = Navigator.SceneConfigs.HorizontalSwipeJumpFromRight;
    var defaultParams = {};

    return (
      <View style={{ flex: 1 }}>
        <Navigator 
          style={styles.navigator}
          initialRoute = {
            {
              name: defaultName,
              component: defaultComponent,
              sceneConfig: defaultSceneConfig,
              params: defaultParams
            }
          }
          configureScene={this.configureScene}
          renderScene={this.renderScene}
        />
        <View accessible={true} style={ {position:'absolute', backgroundColor:'#ffff00', flex:1 }}>
          {
            this.state.LoadingState.isShow ? <LoadingView text={this.state.LoadingState.text} AcIndicShow={this.state.LoadingState.AcIndicShow} /> : null          
          }
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  navigator: {
    flex: 1
  }
});

var AppController = {
  LoadingState: function(LoadingStateData) {}
}

AppRegistry.registerComponent('HL_LY_APP_RN', () => HL_LY_APP_RN);

var instance = null;

export const AppInstance = function() {
  if (instance === null) {
    instance = AppController;
  }
  return AppController;
};


**实现 :

            // 请求数据的网络层提示
            AppInstance().LoadingState({
                isShow:true,
                AcIndicShow:true,
                text:'数据加载中',
            });

调用:

AppInstance().showLoading(false);


Javascript异步编程的4种方法


http://www.ruanyifeng.com/blog/2012/12/asynchronous_javascript.html
常见的浏览器无响应(假死),往往就是因为某一段Javascript代码长时间运行(比如死循环),导致整个页面卡在这个地方,其他任务无法执行。
"同步模式"就是上一段的模式,后一个任务等待前一个任务结束,然后再执行,程序的执行顺序与任务的排列顺序是一致的、同步的;
**"异步模式"则完全不同,每一个任务有一个或多个回调函数(callback),前一个任务结束后,不是执行后一个任务,而是执行回调函数,后一个任务则是不等前一个任务结束就执行,所以程序的执行顺序与任务的排列顺序是不一致的、异步的。

一、回调函数

function f1(callback){
setTimeout(function () {
// f1的任务代码
callback();
}, 1000);
}
f1(f2);

二、事件监听

f1.on('done', f2);
function f1(){
setTimeout(function () {
// f1的任务代码
f1.trigger('done');
}, 1000);
}

f1.trigger('done')表示,执行完成后,立即触发done事件,从而开始执行f2。

三、发布/订阅

我们假定,存在一个"信号中心",某个任务执行完成,就向信号中心"发布"(publish)一个信号,其他任务可以向信号中心"订阅"(subscribe)这个信号,从而知道什么时候自己可以开始执行。这就叫做"发布/订阅模式"(publish-subscribe pattern),又称"观察者模式"(observer pattern)。

jQuery.subscribe("done", f2);
function f1(){
setTimeout(function () {
// f1的任务代码
jQuery.publish("done");
}, 1000);
}
jQuery.unsubscribe("done", f2);

四、Promises对象

简单说,它的思想是,每一个异步任务返回一个Promise对象,该对象有一个then方法,允许指定回调函数。比如,f1的回调函数f2,可以写成:
**好处:如果一个任务已经完成,再添加回调函数,该回调函数会立即执行。所以,你不用担心是否错过了某个事件或信号。这种方法的缺点就是编写和理解,都相对比较难。

'use strict';
import React, {Component} from 'react'


class NetUitl extends Component {

  static request(url, options) {
    let isOk;
    return new Promise((resolve, reject) => {
      fetch(url, options)
        .then((response) => {
          if (response.ok) {
            isOk = true;
          } else {
            isOk = false;
          }
          return response.json();
        })
        .then((responseData) => {
          if (isOk) {
            resolve(responseData);
          } else {
            reject(responseData);
          }
        })
        .catch((error) => {
          reject(error);
          console.log(error);
        });
    });
  }

  /**
  *url :请求地址
  *data:参数(Json对象)
  */
  static postJson (url, data) {
    var fetchOptions = {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    };
    return NetUitl.request(url, fetchOptions);
  }

  //get请求
  /**
  *url :请求地址
  */
  static get(url) {
    return NetUitl.request(url, null);
  }
}

module.exports = NetUitl;

上一篇 下一篇

猜你喜欢

热点阅读