Run specific code only first time into route


#1

Hi,

how can I run a function only the first time user goes in the route?

I’ve seen something about ‘one’ method but I don’t find any examples of how to use it.

I’tried this code:

doSomething: function() { console.log('doSomething for phonebook'); }.one('activate'),

but i get this error

Uncaught TypeError: (intermediate value)(intermediate value).one is not a function

#2
doSomething: function() { console.log('doSomething'); }.on('init')

init → only first time (when the route singleton is initialized)

activate → everytime the route is entered (but not when its model changes)


#3

@spectras thank you for answer. on(‘init’) run the function when application starts up, even if i’m not in the route. I need something to run the code only the first time the users goes into the route. If the user never goes into the route i don’t have to run the code.


#4

Then on(‘activate’) will do. Set a flag the first time it is called so you don’t run the code again.

doSomething: function() {
    if (!this._didSomethingAlready) {
        console.log('doSomething');
        this._didSomethingAlready = true;
    }
}.on('activate')

#5

@spectras it works. thank you.


#6

Alternatively…

The model on route is cached after first load. So the model hook of the route is only called once.


#7

It may not be called at all, if entering the route with a transition/link-to that specified a model. Or, on the other hand, it will be called everytime a transition/link-to is done with a string/number instead of a model.