I try to define some steps ( I call them pages ) in an array and each page should have the possibility to call a function on enter.
My page definition is within an array of pages and the nextHandler ( custom method ) sets the current page index and tries to call the defined function. My React class looks ( abbreviated ) like this:
var App = React.createClass({
pageDefinitions: [
{
title: "Page 1",
enterFunction: this.enterPageOne
}
],
enterPageOne: function() {
console.log("Something useful here");
},
nextHandler: function() {
var st = this.getState();
st.currentPageIndex = st.currentPageIndex + 1;
this.setState(st);
var page = this.pageDefinitions[this.state.currentPageIndex];
console.log(typeof page.enterFunction);
console.log(page.title);
if ( typeof page.enterFunction === "function") {
page.enterFunction();
}
},
getInitialState: function() {
return {
currentPageIndex = -1
};
},
render: function() {
return (
<div>Left out</div>
}
});
While title correctly prints out on console, the function is always undefined. How can I provide a function reference in my array?
Edit: As @gillesc and @justin-morgan pointed out it is a problem of scope ( this is pageDefinition, not the class )
Edit 2: Found solution, I changed pageDefinitions to getPageDefinitions() like this:
getPageDefinitions: funtion() {
var self = this;
return [
{
title: "Page 1",
enterFunction: selfenterPageOne
}
];
}
pageDefinitionsis an array of object, sothisin the first object would reference to the object inside the array and not your main object. So basicallythis.enterPageOneis undefined.