underscore isEqual and JSON

末鹿安然 提交于 2019-12-13 16:26:24

问题


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/



来源:https://stackoverflow.com/questions/19316043/underscore-isequal-and-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!