Documentation

Saving and restoring addon's state

Having added some basic user interaction, it's time to start preserving the addon's state. Without this mechanism, every time a user enters the page where the addon is embedded, a click counter is reset. That's because the addon gets no information that this action was executed before. To add the states to the addon's code, a developer has to implement two methods:

  • presenter.getState() – responsible for collecting information about the addon's current state before leaving the page
  • presenter.setState(state) – responsible for applying preserved state to the addon. In normal conditions (when addon doesn't use any asynchronous methods), this method will be always executed after the presenter.run() method.

Note: At this point, the addon's flow is broken into multiple methods, therefore it's a good practice to save the references to both view and model ones so they can be accessed outside the run and createPreview functions. It can be achieved with just two lines of code:

presenter.$view = $(view);
presenter.model = model;

In order to implement the getState method, it should return String object, which will be passed to the setState method afterwards. When multiple properties describe the addon's state, it's a good practice to use the JSON object.

presenter.getState = function () {  
    return JSON.stringify({  
        clickCounter: clickCounter  
    });  
};

As mentioned above, to apply the preserved state, a developer needs to implement a setState method. In this case, it will parse passed JSON and set clickCounter with a provided number (with updating HTML code accordingly).

presenter.setState = function (state) {  
    var parsedState = JSON.parse(state),  
        $counter = presenter.$view.find('.sample-addon-clicks-counter');  

    clickCounter = parsedState.clickCounter;  
    $counter.text('Count: ' + clickCounter);  
};

A full addon's code at this point is available here.