2

I have a view DialogView which is actually a popup as follows :

var DialogView = Backbone.View.extend({
        events : {
            'click a._save' : '_save',
            'change input._adjust' : '_calculateAdjustedPrice'
        },
        initialize : function(options) {
            this.realModel = options.model;
            this.model = (this.realModel).clone();
        },
        save : function() {
            this.model = this.realModel;
        }
        return DialogView;
    });

In another view, on click of alink the following code executes to open the popup :

var dialogView = new DialogView({
                        model : dialogModel
                    });

IN this DialogView , there are some events fired based on which the model passed to view is changed. There is a button, save on view, which when clicked should keep the changed model as it is(Nothing to do, since model values are changed on events, on clicking of save i have the changed model). But if the DialogView is closed without clicking on save, then the changes made in model should not persist and it should revert to its original state.

I used Backbone's model.clone() method as shown above in DialogView code. But it seems clone() is not creating a copy of original model but simply referring to the same model. Whenever value in this.model change, value in realModel also change. I want that when events are fired then values get changed in the model of DialogView but the original model which was sent to DialogView remain as it is so that if i close the DialogView without saving then the values in model passed to this view remain unchanged.

As per BAckbone documentaion, clone creates a new Instance of a model but my research above seems to give different results. Am i understanding something wrong here?

Gaurav Kumar
  • 1,091
  • 13
  • 31

1 Answers1

0

The dialog model passed to the DialogView had a javascript object. Since clone() does not do deep cloning, the reference of the that object was passed to cloned model. Hence when any property of that object was changed in cloned model, it reflected in original model too.

Gaurav Kumar
  • 1,091
  • 13
  • 31