简体   繁体   English

在没有NodeJs EventEmitter的情况下构建Flux / React应用程序

[英]Building Flux/React application without NodeJs EventEmitter

Hi I'm trying to build a Flux/React application with a go-lang back-end. 嗨,我正在尝试使用go-lang后端构建Flux / React应用程序。 I have been following a tutorial I found here . 我一直在按照我在这里找到的教程。 But I have a problem when building the store. 但是我在建立商店时遇到了问题。 In the tutorial something like this is used to create a base for the store. 在教程中,这样的东西用于为商店创建一个基础。

var ProductStore = _.extend({}, EventEmitter.prototype, {...});

The problem I have is I do not have access to the EventEmitter library which I understand is a Nodejs lib? 我遇到的问题是我无法访问EventEmitter库,我理解它是一个Nodejs库? Is there an alternative I can use? 有没有我可以使用的替代方案?

You can use NodeJS libraries in the browser! 您可以在浏览器中使用NodeJS库! Take a look at browserify . 看看browserify

First some code: 首先是一些代码:

// index.js
var EventEmitter = require("events").EventEmitter;
var ProductStore = function() {};
ProductStore.prototype = new EventEmitter;

Then you run browserify on it: 然后你运行browserify:

browserify index.js > bundle.js

Also worth a look is WebPack which does the same thing. 另外值得一看的是WebPack做同样的事情。 (but has some additional features) (但有一些额外的功能)

Well if you are using the flux implementation given by Facebook ( https://github.com/facebook/flux ), you can actually extends their FluxStore class which comes with a build in eventEmitter. 好吧,如果你使用Facebook( https://github.com/facebook/flux )提供的flux实现,你实际上可以扩展他们的FluxStore类 ,它带有一个构建在eventEmitter中。

The only thing if you want to do that is you must use es6 classes (and use babel to transpile to es5). 唯一要做的就是你必须使用es6类(并使用babel转换为es5)。

The good thing about it is that you don't have to implement the addListener removeListener and emitChange methods, and that's very DRY :) 关于它的好处是你不必实现addListener removeListeneremitChange方法,而且非常干燥 :)

With this solution, your stores will end up looking like that : 有了这个解决方案,您的商店最终会看起来像这样:

var FluxStore = require("flux/utils").Store,
    thing;

class ThingStore extends FluxStore {
    getThing() { 
        return thing;
    }

    __onDispatch(payload) {
       //your code
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM