scoots
scoots

Reputation: 715

How do you maintain view states with Marionette JS?

It seems that Marionette isn't designed to handle reusing views. What is an effective way to maintain view states (for all view types) since they're always being reconstructed?

My first thought was to capture state in the models, but I quickly parted with that idea as many views can reference the same model.

I did try reusing views in a couple of different fashions but wasn't confident what I was doing was correct. In each case, I felt like the Marionette methods I was overriding might break things (now and/or later).

I've found suggestions on how to accomplish this with pure Backbone, and also glanced at Giraffe which seems to handle state quite effectively, but I've yet to find a solution for Marionette.

Upvotes: 4

Views: 1491

Answers (2)

rekarnar
rekarnar

Reputation: 463

An easy unsaved state system for getting data to the template is:

View.MyView = Marionette.ItemView.extend({
    serializeData: function() {
        return _.merge(this.model.toJSON(), this.options.state.toJSON());
    },
});

var view = new View.MyView({
    model: model,
    state: new Backbone.Model(),
});

With a little more advanced version you can use the model events too:

View.MyView = Marionette.ItemView.extend({
    initialize: function() {
        var self = this;

        this.options.state.on('change', function(event, data) {
            if (_.isFunction(self[event])) {
                self[event](data);
            }
        });
    },
});

Then in your controller:

view.options.state.trigger('change', 'functionName', 'someData');

Upvotes: 2

Jo D
Jo D

Reputation: 3

You can track your view states by using a ViewModel.

Sam talks a bit about this here: http://youtu.be/CTr-tTwRH3o

Upvotes: 0

Related Questions