javascript – 将Singleton JS对象转换为使用ES6类 - 代码日志

javascript – 将Singleton JS对象转换为使用ES6类

我正在使用ES6与Webpack es6-transpiler根据我的文章在这里:http://www.railsonmaui.com/blog/2014/10/02/integrating-webpack-and-the-es6-transpiler-into-an-existing-rails-project/

将两个Singleton对象转换为使用ES6类是否有意义?

import { CHANGE_EVENT } from "../constants/Constants";

var EventEmitter = require('events').EventEmitter;
var merge = require('react/lib/merge');

var _flash = null;

var BaseStore = merge(EventEmitter.prototype, {

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },

  getFlash: function() {
    return _flash;
  },

  setFlash: function(flash) {
    _flash = flash;
  }
});

export { BaseStore };

这是一个文件ManagerProducts.jsx,它具有应该从BaseStore扩展的单例。

/**
 * Client side store of the manager_product resource
 */
import { BaseStore } from "./BaseStore";
import { AppDispatcher } from '../dispatcher/AppDispatcher';
import { ActionTypes } from '../constants/Constants';
import { WebAPIUtils } from '../utils/WebAPIUtils';
import { Util } from "../utils/Util";
var merge = require('react/lib/merge');

var _managerProducts = [];

var receiveAllDataError = function(action) {
  console.log("receiveAllDataError %j", action);
  WebAPIUtils.logAjaxError(action.xhr, action.status, action.err);
};

var ManagerProductStore = merge(BaseStore, {
  getAll: function() {
    return _managerProducts;
  }
});

var receiveAllDataSuccess = function(action) {
  _managerProducts = action.data.managerProducts;
  //ManagerProductStore.setFlash({ message: "Manager Product data loaded"});
};


ManagerProductStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;
  if (Util.blank(action.type)) { throw `Invalid action, payload ${JSON.stringify(payload)}`; }

  switch(action.type) {
    case ActionTypes.RECEIVE_ALL_DATA_SUCCESS:
      receiveAllDataSuccess(action);
      break;
    case ActionTypes.RECEIVE_ALL_DATA_ERROR:
      receiveAllDataError(action);
      break;
    default:
      return true;
  }
  ManagerProductStore.emitChange();
  return true;
});

export { ManagerProductStore };
我认为单身人士(管理自己的单身生活的班级)是不必要的。这并不是说单身生命没有用,只是我喜欢类别以外的东西来管理对象的生命周期,比如DI容器。

话虽如此,单例模式可以应用于JavaScript类,借用ActionScript中使用的“SingletonEnforcer”模式。在将使用单例的现有代码库移植到ES6中时,我可以看到想要这样做的东西。

在这种情况下,这个想法是通过公共静态实例getter将私有(通过未公开的Symbol)静态单例实例进行私有化。然后,您可以将构造函数限制为可以访问不在模块外部的特殊单例Enforcer符号。这样,如果除单身人士以外的任何人试图“新”,构造函数就会失败。它看起来像这样:

const singleton = Symbol();
const singletonEnforcer = Symbol()

class SingletonTest {

  constructor(enforcer) {
    if(enforcer != singletonEnforcer) throw "Cannot construct singleton";
  }

  static get instance() {
    if(!this[singleton]) {
      this[singleton] = new SingletonTest(singletonEnforcer);
    }
    return this[singleton];
  }
}

export default SingletonTest

那么你可以像任何其他单身一样使用它:

import SingletonTest from 'singleton-test';
const instance = SingletonTest.instance;
http://stackoverflow.com/questions/26205565/converting-singleton-js-objects-to-use-es6-classes

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:javascript – 将Singleton JS对象转换为使用ES6类