javascript - Prototype methods not seen in NodeJS session -
i'm trying learn javascript , nodejs building small game, , i'm running problem. when attach object session, whenever reaccess session no longer have access prototype methods define on it.
in 1 file called 24.js
, have
function deck() { this.cards = []; (var = 0; < 52; i++) { this.cards[i] = math.floor(i / 4) + 1; } this.done = false; } function gamestate() { // holds game state , game logic this.time = 0; this.score = 0; this.deck = new deck(); this.deck.deal(); } deck.prototype.deal = function() { // not important } var gamemaker = exports = module.exports = function() { return new gamestate(); }
then in main file have
var express = require('express'); var gamemaker = require('./24.js'); var app = express(); app.use(express.static(__dirname + '/static')); app.use(express.urlencoded()); app.use(express.cookieparser()); app.use(express.session({ secret: 'supersecret', key: 'express.sid' })); app.get('/', function (req, res) { if (!req.session.game) { req.session.game = gamemaker(); } var game = req.session.game; // access data game send client }); app.post('/verify', function (req, res) { // assumes game exists, check later var game = req.session.game; game.score += 1; game.deck.deal(); res.redirect("/"); });
i error whenever post, because says object #<object> has no method 'deal'
. checked , can still call deal()
method first time load page, , can access other information (like score of game, or cards last dealt.) thing breaks method calls on same session.
the problem when sessions saved between requests, serialized json.stringify(req.session)
. means objects converted plain js objects , object no longer have prototype set deck.prototype
when parsed json.
you should not storing complex data structures in session. instead have own logic get/set session values needed recreate deck.
Comments
Post a Comment