Search code examples
backbone.jsmarionette

Listen change in a variable in Marionette object?


Which event method can help to capture a change to a value set to 'variable' defined in marionette object.

e.g:

var LoginModule = Marionette.Object.extend({

    initialize: function(options) {
        this.state = 'pending';
    },

    init: function(model) {
        model.fetch({validate:true})
        .done(function() {
            this.state = 'success';
        })
        .fail(function(res){
            console.log(res);
            this.state = 'failed';
        });

        return model;
    }
});

Here I want to detect change to variable this.state. Is there is option to fire once, like listeToOnce?

Usage:

var loginM = new LoginModule(); loginM.init(model);


Solution

  • Edit: I guess i found better solution for you. Try like below. Firstly, change your init method like this.

    init: function(model) {
            model.fetch({validate:true})
            .done(function() {
                this.state = 'success';
                this.triggerMethod('state:changed');
            })
            .fail(function(res){
                console.log(res);
                this.state = 'failed';
                this.triggerMethod('state:changed');
            });
    
            return model;
        }
    

    After that you could catch event state:changed like below:

    this.on("state:changed", function(){
         //handle your changed state
    });