HTML and CSS Reference
In-Depth Information
Backbone . serverSync ( 'update' , model , { success : 'foo' , error : 'bar' }).
If the server responds with a different ID than what is stored on the client, then that
means you have a new object. If the IDs remain the same, however, then you simply
have an update. When a new object comes from the server, the following code deletes
the existing ID in localStorage and adds the new version:
for ( var i = 0 ; i < models . length ; i ++ ) {
var model = models [ i ];
if ( model . get ( 'synchronized' )) { continue ; }
model . change ();
Backbone . serverSync ( 'update' , model , {
success : function ( data ) {
var model = collection . get ( data . ClientId );
//if new server will return a different Id
if ( data . ServerId != data . ClientId ) {
//delete from localStorage with current Id
Backbone . sync ( "delete" , model ,
{ success : function () { },
error : function () { } });
//save model back into localStorage
model . save ({ Id : data . ServerId })
}
model . save ({ synchronized : true });
collection . localCacheActive = false ;
},
error : function ( jqTHX , textStatus , errorThrown ) {
console . log ( 'Model upload failure:' + textStatus );
collection . localCacheActive = false ;
}
});
}
When asked to pull server-side changes to a collection from the server, the client first
uses model.save() to save any unpushed client-side changes into localStorage . It next
requests the entire collection from the server via the standard Backbone fetch method:
tempCollection . sync = Backbone . serverSync ;
tempCollection . fetch ( { success : blah , error : blah });
In practice, you could reduce the associated data download to only items that require
updating. As it receives each model back from the server, the success function checks
each one against its own list. If the model is new, success adds it to the collection that
is updating and also uses model.save() to record it into local storage:
collection . add ( tempModel );
tempModel . change ();
tempModel . save ({ synchronized : true });
Finally, the success function updates the model with revised data after the model has
been synchronized:
Search WWH ::




Custom Search