Does everything in Marionnette have to be an object or collection - backbone.js

I am writing an app which will send orders to a remote server. I have a lot of the logic done now for setting up new orders. Items are added to a cart, cart totals are created and I am now ready to hit the server endpoint. At the moment, the REST API (which is being built by a separate team) needs me to:
Send a new order request and receive a new order number
Loop through my cart sending each item individually to the new order endpoint
Send the order totals
Send the payment options and amounts
Return the final data as a receipt to the customer
I currently have
- A cart collection which contains item models
- A totals model
I am not looking for code particularly but could someone outline a method to send the data to the server. I'm trying to figure how to use collections and API URI endpoints to do this but don't have any precedent to follow. Would it be natural in a Marionette/Backbone app to use direct POST requests to the server using defferds and promises or is there a better approach?
I would appreciate any pointers in the right direction,

Generally you wouldn't/shouldn't need to use direct POST requests when interacting with a REST API. Backbone models and collections are designed to interact with an API following this model out of the box.
If you define a collection as so:
var Items = Backbone.Collection.Extend({ url: '/items' });
var myItems = new Items();
myItems.fetch();
then when you call 'fetch' on the collection a GET request will be issued to your specified URL which will populate the collection with the models returned. You can add models to this collection which will fire the appropriate requests to the endpoint. eg. a POST. the default mappings are below for the above collection:
create -> POST '/items'
read -> GET '/items[/id]'
update -> PUT '/items/id'
delete -> DELETE '/items/id'
A lot of this is overridable and configurable so that you can fit into the API that your building against.

Related

AngularJS - How to add child objects during edit and then PUT

I'm getting started with AngularJS with Web API and EF on the back end. I have an edit form that is populated via a GET request which returns a Boat object. One of Boat's properties is an Images array.
If the user adds images to Boat then I need records to be inserted into the database for each new image when the boat is updated. (But obviously not for images that the boat already had prior to edit.)
The current Web API function is:
public async Task<IHttpActionResult> Put(int id, Boat boat)
It seems I could either:
a) Push any newly added images to $scope.Boat.Images prior to the PUT. Then in the Web API function, loop through the received Boat.Images, check if a database record exists for that image, if no record exists add the image record to the database. This seems a bit uneconomical because I'm looping through every existing image and checking if it actually exists in the db already.
or
b) Send a separate object "newImages" with the PUT. Then I guess the Web API function would be:
public async Task<IHttpActionResult> Put(int id, Boat boat, string[] newImages)
This would have the benefit of not having to check which images already exist vs new ones. ie. Everything in newImages gets added to the database. But, is it weird from an AngularJS point of view to separate the new images from the Boat.Images collection?
Would you do a) or b) or... c) some other way?
I'll do A as it fits more the Restful approach.
Now Images could be an Array of complex object instead of Array of string, therefore you would have a property ID.
Then on the WebAPI side, you just add the Images without IDs set.
var newImages = Boat.Images.Select(x => x.Id == null);

Angular ngResource with AppEngine Cursor

I'm using Google AppEngine as backend and AngularJS as front end for web application I'm making. I'm presenting data in pages to the user.
AppEngine has the ability to select data and return 3 pieces of information: the items selected, indication if there are more items and cursor for the next page.
I need to return all 3 pieces to the client app so it can present the fetched items and allow the user to go to the next page.
I also would like to use ngResource to interact with the server.
The problem is that ngResource expect the list of items to be a list and here it is an object with the 3 pieces.
Is there a way to modify ngResource a bit so that after fetching the data it will use the items to build the array of items?
Not necessarily, ngResource can deal with arrays as well as single item or json object. The standard get operation returns a object whereas query returns array. Bottom line as long it is a valid json data ngResource would work.
You can always call get on the resource, get the data into a json object and then it can have sub-properties which can be of array type.
You can share your specific structure and the community can help you with understand how to access it using ngResource

ExtJS CRUD operations on Grid Panel and Grails backend

I am an absolute novice and have been working and struggling with ExtJS ! I am supposed to get a list of user records and dipslay them on Ext grid Panel. I have an ExtJS frontend and Grails ( Groovy Controllers ) backend. I have referred to a few links like:
http://docs.sencha.com/extjs/4.0.7/#!/example/grid/row-editing.html
http://docs.sencha.com/extjs/4.0.7/#!/example/restful/restful.html
http://docs.sencha.com/extjs/4.0.7/#!/example/writer/writer.html
The api property ( or ) tag ( or )attribute ( I don't know what it is called ) helps me in getting the list of JSON objects to be displayed in the Grid. Also, when I select a row and click on Delete, the request is reaching the delete action in my controller. But my problems begins here: how do I make sure that:
1) the selected row is deleted from Database? How do I pass the identifier or something to controller so that it will delete the record?
2) When I add a row, how do I pass the field values to backend Controller?
Most of the code is same as given in the restful link above. For reference, this is my Datastore:
https://docs.google.com/document/d/1gQyLCt6xWXTm-OUgYu7hku47r5WcS0my5yPBSKj2B7I/edit?usp=sharing
If you use a Rest proxy, ExtJS will auto generate the urls for you, based on the url stub that you specify. So if your proxy is configured to point to something like: /api/users, the following urls would be generated for each of the 4 actions:
read: /api/users (GET)
create: /api/users (POST)
update: /api/users/SomeIDFromTheUpdatedRecord (PUT)
delete: /api/users/SomeIDFromTheDeletedRecord (DELETE)
As you can see, the end point for each request is precisely the same (api/users), but for PUT and DELETEs, the id of the affected record is included in the URL automatically.
And of course, with POST and PUT requests, you can add any additional params that you'd like to send through to the server, although this will be done automatically when you persist the model instance via the store's configured proxy.

How to identify a BackboneJS Model serverside

I'm just getting my head around BackboneJS, but one of the (many) things I'm still struggling with is how exactly the Models Sync up and relate to the serverside DB records.
For example, I have a Model "Dvd", now I change an attribute on the "Dvd" Model, the Name for example, and then I call save(), how exactly does the server side know what DB record to update? Does Backbone hold the DB row ID or something else?
Yes, typically you will set up your Backbone models so that they have database row IDs for any objects you're working with. When one of them is brand new on the client side and not yet saved to the server, it will either have a default or no ID, which doesn't matter since the server will be assigning the ID if and when the initial save transaction succeeds.
Upon saving or updating a model item, Backbone expects the server to reply with some JSON that includes any attributes that have changed since the save or update request was made. In the response to the initial save request, the server informs the client of a newly saved item's row ID (and you can also send along any other information you might need to pass to the client at the same time).
By default, the 'id' attribute of a model object is assumed to be its unique identifier, but backbone lets you change this if you're using a different identifier for the primary key. Just give your model an idAttribute parameter (see the docs for Backbone.Model.extend()) to do that.
Meanwhile, either the urlRoot parameter or a url function can be given to your models to characterize the urls that should be used to send the various ajax requests to the server for a given model.

How to generate model id's with Backbone.js

I am setting up the backbone sync mechanism and am a bit confused where to generate the id's for the models.
When I create a new model, should backbone be generating and setting the id, or am i supposed to implement an id generation method, or is there some sort of mechanism where I "PUT" the data to the server, which generates the id and returns a model with the id?
I'm providing a second answer to simplify the code you need to study to get the main points you're pondering about - the actual round about from model to server and how ids play their role.
Say you define a model - Let's go with Jurassic Park.
// Define your model
var Dinosaur = Backbone.Model.extend({
defaults: {
cavemanEater: undefined // Has one property, nom nom or not.
},
urlRoot: 'dino' // This urlRoot is where model can be saved or retrieved
});
var tRex = new Dinosaur({'cavemanEater':true});
You now have instantiated a dinosaur that is a meat eater. Roar.
console.log(tRex);
What you should notice is that in the properties of tRex, your model does not have an id. Instead, you will see a cID which you can think of as a temporary id that Backbone automatically assigns to your models. When a model doesn't have an id it is considered new. The concept of persisting a model (either to a database or local storage) is what allows you to go back to that resource after you've created it and do things like save (PUT) or destroy (DELETE). It would be hard to find that resource if you had no way to point directly at it again! In order to find that resource, your model needs an id, something it currently does not have.
So as the above answers have explained it is the job of your database (or localstorage, or some other solution) to provide Backbone with a resource id. Most of the time, this comes from the resource id itself, aka - the primary key id of your model in some table.
With my setup, I use PHP and mySQL. I would have a table called Dinosaur and each row would be a persistent representation of my dino model. So I'd have an id column (unique auto-incrementing int), and cavemanEater (bool).
The data communication flow happens like this.
You create a model.
The model is new so it only has a cID - no proper ID.
You save the model.
The json representation of your model is SENT to your server (POST)
Your server saves it to the table and gives it a resource id.
Your server SENDS BACK a json representation of the data {id:uniqueID}
Backbone RECEIVES this json representation with id
Backbone automagically updates your model with an id.
Here is what annotated code looks like.
CLIENT:
tRex.save();
// {'cavemanEater':true} is sent to my server
// It uses the urlRoot 'dino' as the URL to send. e.g. http://www.example.com/dino
SERVER:
// Is setup to accept POST requests on this specific ROUTE '/dino'
// Server parses the json into something it can work with, e.g. an associative array
// Server saves the data to the database. Our data has a new primary id of 1.
// Data is now persisted, and we use this state to get the new id of this dino.
$dinoArray = array('id'=>1, 'cavemanEater'=>true);
$dinoJSON = json_encode($dinoArray);
// Server does something to send $dinoJSON back.
CLIENT:
// If successful, receives this json with id and updates your model.
Now your tRex has an id = 1. Or should I say...
tRex.toJSON();
// RETURNS {'id':'1', 'cavemanEater':'true'}
Congrats. If you do this tRex.isNew() it will return false.
Backbone is smart. It knows to POST new models and PUT models that already have a resource id.
The next time you do this:
tRex.save();
Backbone will make a PUT request to the following URL.
http://www.example.com/dino/1
That is the default behavior by the way. But what you'll notice is that the URL is different than save. On the server you would need a route that accepts /dino/:id as opposed to /dino
It will use the /urlRoot/:id route pattern for your models by default unless you tweak it otherwise.
Unfortunately, dinosaurs are extinct.
tRex.destroy();
This will call... Can you guess? Yep. DELETE request to /dino/1.
Your server must distinguish between different requests to different routes in order for Backbone to work. There are several server side technologies that can do this.
Someone mentioned Sinatra if you're using Ruby. Like I said, I use PHP and I use SLIM PHP Framework. It is inspired by Sinatra so it's similar and I love it. The author writes some clean code. How these RESTful server implementations work is outside the scope of this discussion though.
I think this is the basic full travel of new Backbone data with no id, across the internets to your server where it generates, and sends back the resource id, to make your model live happily ever after. (Or destroy() not...)
I don't know if this is too beginner for you but hopefully it will help someone else who runs into this problem. Backbone is really fun to program with.
Other similar Answers:
Ways to save Backbone JS model data
or is there some sort of mechanism where I "PUT" the data to the server, which generates the id and returns a model with the id?
Kind of. When you call the save method of your model, backbone make a POST XHR and your application server should respond with JSON contains an id.
You can see an example here: http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/
Quoting from the link:
post '/api/:thing' do
# parse the post body of the content being posted, convert to a string, insert into
# the collection #thing and return the ObjectId as a string for reference
oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.tos))
"{\"id\": \"#{oid.to_s}\"}"
end
If you don't know Ruby keep in mind what the last expression that is evaluated is automatically returned by the method.
What I understand from your question is that you want to have a collection with models that exist on the server. In order to get these models into the collection you'd have to add call 'fetch()' on the collection.
The url would be "/users" or something similar, that would have to return an array of objects with user data in there. Each item in the array would then be passed to UserCollection.add(). Well, actually it would be passed all at once, but you get the point.
After this your collection is populated. The url on the Model is meant for updating and saving the individual model. The url of the collection will also be used for creating models. Backbone's sync is RESTful, like Ruby on Rails. You can actually learn more about it on the documentation of Ruby on Rails:
http://guides.rubyonrails.org/routing.html
What you would generally do is have a different url for your model than for your controller. After populating your collection you have id's for each model in there because they came from the server.
Now when you add a new model based on user input you'd do something like this:
var HomeModel = Backbone.Model.extend({
defaults: {
lead: "not logged in",
},
url: 'test.php',
initialize: function(){
_.bindAll(this, 'handleSave', 'handleError');
// Save already knows if this.isNew.
this.save(undefined, {success: this.handleSave, error: this.handleError});
},
handleSave: function(model, response){
this.model.reset(model);
},
handleError: function(){
},
});
var HomeView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.model = new HomeModel();
this.model.bind("change", this.render);
},
el: 'div',
render: function() {
// Do things to render...
}
});
var homeView = new HomeView();
The example is from someone else's question I answered, I just add the relevant things.
The general idea is to save the model when it is created, if you need it somewhere else you can just move the code into a function of the model and call that based on events or anything else.

Resources