Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS window.addEventListener("hashchange") not working

I have a React component called Home. Within Home, I have a function "urlListener" in which I have added an event listener to alert whenever the URL is being changed.

var Home = React.createClass({
	getInitialState: function () {
		return {
			openedFile: this.props.location.query.file || '',
			apps: [],
			showNav: this.props.location.query.file ? false : true,
			layout: 'row',
			cloneAppName: 'New Application',
			appName: 'Application Name',
			showSave: false
		}
	},
	urlListener: function(){
		window.addEventListener("hashchange", function(){
                       saveUnsaved();
		});
	},
        saveUnsaved: function(){
        }

The listener works fine and is being called whenever there is a change in the URL. However, the console says that the function I'm trying to call is not a function. I am new to React and any help on this would be appreciated.

like image 958
Edwin Samuel Jonathan Avatar asked Oct 30 '22 15:10

Edwin Samuel Jonathan


1 Answers

Someone had commented the answer which seemed to work for me, but the comment was removed before I could accept the answer. The correct way of doing it is

{() => this.saveUnsaved();}

The arrow function apparently switches the context from "window" to "this"(the current component) internally. Without the arrow function, "this" would be referring to the "window" component.

like image 118
Edwin Samuel Jonathan Avatar answered Nov 15 '22 05:11

Edwin Samuel Jonathan