How error handling is done in Backbone.js save()? - javascript

I have a backbone model. Now I want to update the model on server side, so I call model.save(); now as backbone.js makes an ajax call to server with PUT request. If the server fails to process this request, it sends some error code to client.
Now my question is, client has model's updated state, and server has an old state, both are inconsistent. Now on error() callback of my model.save() I want to revert the model to old state, how would I do it? Does backbone keeps copy of old state with it?

try using
oldMOdel = newModel.previousAttributes();
check out this

Related

Vue js and favorite/like button

I'm wondering how favorite, subscribe or like buttons work.
I don't understand something.
For exemple:
A user like a post with id 243.
A ajax request is sent to the server with the id of the post (243) [here comes back end stuff, the user's favorite list is updated, including that post] and the server sends back a success response.
Now, how I suppose to deal with modifying the like button to actually display that is liked (permanently, including refresh).
How can I achieve that in Vue JS. How things get updated? I don't understand this part.
If the server sends back a successful response you can increment the number that is already there.
This initial number is something you have gotten either through a prop, directly from the server or through an initial AJAX request.
If you want to "permanently" update the amount of likes on your button you have to persist it to a database(or some other storage medium). On you server you could have a route that accepts a post id as an argument and increment that specific user post:
/incrementlike/243
That is where you would make a POST ajax request to. Most of the time in an MVC framework you would have a controller action/method mapped to this route that holds the logic to respond to this call.
If you are interested in the part that happens after you make an AJAX request to the server to increment your like on the backend side, I suggest you read up on routing or MVC structure.
How you would do this is really done on a case by case basis. It really depends on a number of things, for example what your backend does to a post when it is liked.
If you would like a general 'explanation' to the process I attach it below, this is not really Vue specific, but the general idea is the same:
Frontend side:
Modify the local state of you post to set the proper flag, ex. post1.liked = true immediately when it is clicked, before sending the request to the server.
Make sure your GUI represent this change. ex. Base the color of the button on the property 'liked' of each post.
If a failure response it received from the server, notify the user and allow them to 'try again' or something similar.
When refreshing the page, make sure changes are fetched from the server, If you have done the backend part correctly, the modification of the state of the post will be correct in the data you receive from your backend (post1.liked will be true)
Backend side
When the request comes in, modify the state of the post the correct way and make sure that next time the post is fetched, the new state is sent.

Using Different Objects In Array Model AngularJS

I am very new to angular and this one is striking in my head a lot. So scenario is : Suppose angular http returns me model containing array of object like:
[{name:"Ankur",lastName:"aggarwal",updation_date:"23-08-2014"},{name:"xyz",lastName:"abc",updation_date:"29-08-2013"}]
Out of this updation_date is not required but coming for some reason. So is it right to update the array with third object without creation date like {name:"def",lastName:"jbc"} . Is it a good practice or array object model should be consistent?
Also what should be the approach? Update the model array first so binding take place instantly, then send it to the server or send it to server and get the updated object? Might be basic one but very new to angular and JMVC.
Is it a good practice or array object model should be consistent?
It depends , if backend expects all array entries to contain updation_date then you have no choice and are forced to add some sensible default value. However, if possible then avoid sending too much unnecessary data from backend since it impacts application performance(like data transfer, adding unnecessary logic to generate sensible default values, etc.)
Update the model array first so binding take place instantly, then
send it to the server or send it to server and get the updated object?
If the nature of your application permits reverting model value when save is unsuccessful then just go ahead with
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Update model.
2.Send data to backend
3.If something bad happens then execute error handling depending on app needs
However if presenting consistent value in the GUI is uttermost importance(e.g. finance applications) then
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Show some message to user like "saving"
2.Perform ajax request
3.If successful, update model, else execute error handling depending on app needs
It depend on your error handling.
As saving on the server-side might be not successful, you should take it into consideration.
My approach is to
Update angular object immediately
Then send AJAX request to server and
Wait for response. If error happen during server save, you shoulde:
revert values,
repeat AJAX
show information to user.

Correct scheme to persistently update a model of a collection in Backbone app

In Backbone terms, What is the correct scheme to persistently update a model which is a member of a collection and reperesented in the user interface?
By utilising a DOM event and method in the view.
Then grabbing the id of the element to be processed by from the event objects, eg. from click.
finding the model in the collection, by findWhere.
Then using set on the model changing attributes.
Then using save() on the model to update the model on server side and client side.
But one may need to wait for success on server side process and only then update the client side model and collection. This can be done by {wait: true} in order to wait server response, but does this mean if and only if the server process succeeds to persist the model in the db this attributes will be set in the client side model. What if it fails on server side what about the preceding lines that set() the model found.
Also adding the new state of the model into the collection.
Lastly, re-rendering the view with the new state of the collection.
It sounds a little bit like you may be wanting 2-way data binding.
Backbone.Stickit is a great plugin for that.

Server-side Changes to Model not Reflected in UI - EmberJS

I'm persisting my model from my controller via a call to this.get('model').save(). This results in a PUT to an endpoint that just returns a 200 message and nothing further. On the server side however, some custom rules are in place that are changing the data so that it's different than what Ember sent to the server. This puts my UI and my persistence tier into an inconsistent state.
What's the correct way to make sure the UI reflects what the correct state of the data after it was persisted to the server? Should my server-side endpoint return the updated model? I've tried just calling this.get('model').reload() after the save() but the UI isn't updating. When I did this I could see that it's asking and getting the new model from the server but as I said, it's not reflected in the UI.
I feel like there's some knowledge fundamental to Ember that I'm missing. Thanks for the help.
I guess that you are not waiting for the record to complete the updating process.
http://emberjs.com/api/data/classes/DS.Model.html#method_reload
So this would be:
this.get('model').reload().then(function() {
console.log("Now I am ready !");
})
Always remember that javascript is async.

What exactly happens when you save a Backbone model?

What exactly happens when you save a Backbone model? Here's the best I can piece together by reading the documentation here:
model.save([attributes], [options]) is called
A "change" event is fired (but only if the attributes are new)
The server is notified of the change?
A "sync" event is called once the server returns
But I'm a Backbone noob and I'm sure someone else could do a way better job of explaining.
I'm partly just curious what happens. I'm also having trouble understanding how Backbone comes up with the JSON object it sends to the server. I'm having a separate problem where the JSON object is not what I want it to be, but I don't know how to change it.
The detailed process can be found in the annotated source code for Backbone.Model.save and Backbone.sync.
If you ignore options.wait and options.silent, your decomposition is mostly correct.
When you issue a model.save:
the attributes passed to the function are set, a change event is fired if the values changed
save delegates the request to model.sync or Backbone.sync
sync serializes the data to a JSON string by calling JSON.stringify(model.toJSON())
An Ajax request is sent to sent to server, a POST request for a new object, a PUT for an update. The target URL is defined by model.url (or collection.url/id)
When the request completes, the model is updated with the server response, if any, and triggers a change event accordingly.
Success or error callbacks are called, a sync event is triggered if no success callback is defined.
Usually, you can customize this behaviour by overriding model.toJSON or model.sync
first,I suggest you read the source code of the backbone, is really very simple.Default backbone and server-side interaction is achieved through backbone.sync.
second,You can trace debug model.save method of code again, naturally know the details.
I suggest you start hereļ¼š
http://backbonejs.org/examples/todos/index.html

Categories

Resources