在不使用Node.js EventEmitter的情况下构建Flux/React应用程序。

huangapple go评论113阅读模式
英文:

Building Flux/React application without NodeJs EventEmitter

问题

嗨,我正在尝试使用Go语言后端构建一个Flux/React应用程序。我一直在按照我在这里找到的教程进行操作。但是在构建存储库时遇到了问题。在教程中,使用以下代码创建存储库的基础:

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

我的问题是,我无法访问EventEmitter库,我了解到它是一个Node.js库。有没有其他替代方案可以使用?

英文:

Hi I'm trying to build a Flux/React application with a go-lang back-end. 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? Is there an alternative I can use?

答案1

得分: 8

你可以在浏览器中使用NodeJS库!看一下browserify

首先是一些代码:

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

然后你在其上运行browserify:

browserify index.js > bundle.js

还值得一看的是WebPack,它也可以做同样的事情(但有一些额外的功能)。

英文:

You can use NodeJS libraries in the browser! Take a look at 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 index.js > bundle.js

Also worth a look is WebPack which does the same thing. (but has some additional features)

答案2

得分: 2

如果你正在使用Facebook提供的Flux实现(https://github.com/facebook/flux),你可以扩展他们的FluxStore类,该类内置了一个事件发射器。

唯一的要求是你必须使用ES6类(并使用Babel将其转译为ES5)。

好处是你不需要实现addListenerremoveListeneremitChange方法,这样就能避免重复代码(DRY原则)。

使用这种解决方案,你的store代码将如下所示:

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

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

    __onDispatch(payload) {
       //你的代码
    }
}
英文:

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.

The only thing if you want to do that is you must use es6 classes (and use babel to transpile to 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 在不使用Node.js EventEmitter的情况下构建Flux/React应用程序。

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
    }
}

huangapple
  • 本文由 发表于 2015年5月6日 05:04:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/30063222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定