Moustachio
Moustachio

Reputation: 184

Backbone.js Persisting child variables to parent

What is the correct way to persist an inherited variable, on action to the parent in Backbone.js? I can see some logical ways to do this but they seem inefficient and thought it might be worth asking for another opinion.

The two classes are both views which construct a new model to be saved to a collection, the parent passing a variable through to a popup window where this variable can be set.

Upvotes: 1

Views: 1879

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55678

I'm not sure there's enough detail in your question to answer, but there are a few ways to to do this:

  • Share a common model. As you describe it, you're using two views to construct a model, so the easiest way is probably to pass the model itself to the child view and have the child view modify the model, rather than passing any variables between views:

    var MyModel = Backbone.Model.extend({});
    
    var ParentView = Backbone.View.extend({
        // initialize the new model
        initialize: function() {
            this.model = new MyModel();
        },
    
        // open the pop-up on click
        events: {
            'click #open_popup': 'openPopUp'
        },
    
        openPopUp: function() {
            // pass the model
            new PopUpView({ model: this.model })
        }
    });
    
    var PopUpView = Backbone.View.extend({
        events: {
            'change input#someProperty': 'changeProperty'
        },
    
        changeProperty: function() {
            var value = $('input#someProperty').val();
            this.model.set({ someProperty : value });
        }
    });
    
  • Trigger an event on the parent. If for some reason you can't just pass the value via the model, you can just pass a reference to the parent and trigger an event:

    var ParentView = Backbone.View.extend({
        initialize: function() {
            // bind callback to event
            this.on('updateProperty', this.updateProperty, this);
        },
    
        updateProperty: function(value) {
            // do whatever you need to do with the value here
        },
    
        // open the pop-up on click
        events: {
            'click #open_popup': 'openPopUp'
        },
    
        openPopUp: function() {
            // pass the model
            new PopUpView({ parent: this })
        }
    });
    
    var PopUpView = Backbone.View.extend({
        events: {
            'change input#someProperty': 'changeProperty'
        },
    
        changeProperty: function() {
            var value = $('input#someProperty').val();
            this.options.parent.trigger('updateProperty', value);
        }
    });
    

Upvotes: 5

Related Questions