【发布时间】:2018-05-06 15:00:45
【问题描述】:
this.on('change', callback);
和
this.removeListener('change', callback);
我的addChangeListener 和removeChangeListener 没有工作。我已经导入了 EventEmitter 并将其与对象分配 ("object-assign": "^4.1.1") 一起使用。
但它会产生错误:
bundle.js:41229 未捕获类型错误:this.on 不是函数
在 Object.addChangeListener (bundle.js:41229)
在 Authors.componentWillMount (bundle.js:40504)
在 callComponentWillMount (bundle.js:26260)
在 mountClassInstance (bundle.js:26356)
在 updateClassComponent (bundle.js:27725)
在 beginWork (bundle.js:28366)
在 performUnitOfWork (bundle.js:31198)
在 workLoop (bundle.js:31227)
在 HTMLUnknownElement.callCallback (bundle.js:19504)
在 Object.invokeGuardedCallbackDev (bundle.js:19542)
这是我的代码:
"use strict";
import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/actionTypes';
import { EventEmitter } from 'events';
import assign from 'object-assign';
import _ from 'lodash';
var CHANGE_EVENT = 'change';
var _author = [];
var AuthorStore = assign({}, EventEmitter.protoType, {
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
emitChange() {
this.emit;
},
getAllAuthors() {
return _author;
},
getAuthorById(id) {
return _.find(_author, {
id: id
});
}
});
AppDispatcher.register(function(action) {
switch (action.actionType) {
case ActionTypes.INITIALIZE:
_author = action.initialData.authors;
AuthorStore.emitChange();
break;
case ActionTypes.UPDATE_AUTHOR:
var existingAuthor = _.find(_author, {
id: action.author.id
});
var existingAuthorIndex = _.indexOf(_author, existingAuthor);
_author.splice(existingAuthorIndex, 1, action.author);
AuthorStore.emitChange();
break;
case ActionTypes.CREATE_AUTHOR:
_author.push(action.author);
AuthorStore.emitChange();
break;
case ActionTypes.DELETE_AUTHOR:
_.remove(_author, function(author) {
return action.id === author.id;
});
AuthorStore.emitChange();
break;
default:
}
});
export default AuthorStore;
我不知道为什么它不起作用,我一直在提到这个documentation。 谢谢。
【问题讨论】:
-
试试 console.log(this.on) 看看它是什么以及它是否可用
-
它返回 undefined...@fatahn
-
当您在
var AuthorStore = assign({}, EventEmitter.protoType, {下方的console.log(this) 时,this指的是什么? -
{addChangeListener: ƒ, removeChangeListener: ƒ, emitChange: ƒ, getAllAuthors: ƒ, getAuthorById: ƒ} addChangeListener : ƒ addChangeListener(callback) emitChange : ƒ emitChange() getAllAuthors : ƒ getAllAuthors() getAuthorById : ƒ getAuthorById(id) removeChangeListener : ƒ removeChangeListener(callback) __proto__ : Objectvar AuthorStore = assign({}, EventEmitter.protoType, {返回错误后无法完成。
标签: javascript reactjs events eventemitter