underscore isEqual and JSON

2019-07-20 20:54发布

问题:

I have a question using underscore isEqual to compare two JSON strings. Currently i have done an app in backbone, and I'm using _.isEqual(savedModel.toJSON(),changedModel.toJSON() ) to detect if the model has changed in the page and promt a "You have unsaved changes, do you want to save?" dialog if the user tires to navigate away.

For some reason I get the dialog in random places even though I have done nothing or have saved changes. Debugging is driving me crazy.

Could this be because JSON does not guarantee the order of the objects in the JSON and underscores isEqual does not handle this case properly? So even if the models are the same, some attributes in the JSON might be different and it returns false?

Pseudocode:

//when entering the page the original model is cloned, when user does changes to the   
//page, the model is cloned again
var savedModel = currentModel.clone().toJSON();

//when the user tries to navigate away from the page
if( _.isEqual(savedModel, model.toJSON() ){
    showSavePromptDialog();
}

回答1:

Following the chain of functions used by backbone.toJSON(), it appears _.extend is used to copy the object and _.extend uses a for..in loop to iterate over the object. for..in iterates over an object in arbitrary order, which is likely the source of your problem.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in



回答2:

Hi this deep equals implementation done to solve similar problem, but I might have missed out some finer details, it was serving well for my purpose.

http://yui3.wordpress.com/2013/04/22/deep-compare-in-javascript/