Michael Tot Korsgaard February 2016

JS funtions in object disapears

When I initially call this function:

var session = function(){
    console.error(service.get());
    if(service.get().session === undefined){
        $localStorage.user.session = {
            timeLeft: 0,  //  Time left until a user session ends (in minutes).
            start: function(timeLeft) {
                $localStorage.user.session.timeLeft = timeLeft;
                $localStorage.user.session.interval;
            },
            stop: function(){
                $interval.cancel($localStorage.user.session.interval);
            },
            interval: $interval(function () {
                $localStorage.user.session.timeLeft -= 1;

                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 0.125 * 60000)
        };
    }

    return $localStorage.user.session;
};

from

function sessionRestart(){
    session();
};
sessionRestart();

It creates the session object with all its variables, but when I reload the page it doesn't populate the variables which are functions. How can I fix that?


EDIT The application is AngularJS and I'm using ngStorage for the $localStorage, and the code is meant for a user session which can be found in a factory in my application.

Answers


Michael Tot Korsgaard February 2016

MarcosPĆ©rezGude made me think of a solution to the problem. Which were to move the $interval outside of the $localStorage which fixed my problem. Not sure why it wouldn't work thou.

The code now looks like this:

var session,
    startSession: function(timeLeft) {
        if($localStorage.user.session === undefined){
            if(timeLeft === undefined){
                timeLeft = 0;
            }

            $localStorage.user.session = {
                timeLeft: timeLeft
            };
        }

        if (session === undefined) {
            session = $interval(function () {
                $localStorage.user.session.timeLeft -= 1;

                if($localStorage.user.session.timeLeft === undefined){
                    service.stopSession();
                }

                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 1 * 60000);  //  Time in milliseconds. Minutes * milliseconds = total milliseconds before the interval repeats.
        }
    },
    stopSession: function() {
        $interval.cancel(session);
        session = undefined;
    };

Post Status

Asked in February 2016
Viewed 3,448 times
Voted 4
Answered 1 times

Search




Leave an answer