Override url and parse in Backbone collection - javascript

I want to override the collection for development purpose (return fake json results from a JSON var or JSON file). But I got error doing below with url
http://jsfiddle.net/qhoc/uZhM8/
GET http://fiddle.jshell.net/_display/[object%20Object],[object%20Object] 404 (NOT FOUND)
However, if I use parse, it seems the parse got executed right after initialize because of both my console.log results show the same thing
http://jsfiddle.net/qhoc/uZhM8/1/
So how to override the url so that fetch can add another JSON at some point (in separate function)?

The url of a collection is supposed to return a URL which will be used with $.ajax to talk to the server:
url collection.url or collection.url()
Set the url property (or function) on a collection to reference its location on the server. Models within the collection will use url to construct URLs of their own.
Your url method is returning an array and Backbone is treating that like a URL string, hence the odd looking URL that produces your 404.
You have some options:
Use a URL that uses jsfiddle's AJAX stubbing tools to produce the necessary JSON.
Override sync to use some inlined JSON instead of a $.ajax call.
Override fetch to use some inlined JSON instead of calling sync.
If you're only concerned about fetching data then all three should work, if you need to simulate saves or deletes, then you'll probably end up overriding sync.

Related

What is the right way to pass array of objects with redirect?

I'm using node.js and I need to pass an array of objects with res.redirect(),
I tried with querystring but it's not a good idea because the array with too big and I could get Error 414 Request URI too long.
using connect-flash isn't a good way either, it's more useful for passing messages.
And I don't want to use req.app.locals for that.
Hope you can help me with any idea.
Assuming the client here is a browser that you want to just automatically follow the redirect and then inherit some new state when the server generates the page for that newly redirected URL, then here are some options:
If you already have a session established for the user, then you can store the data in the session, then include a single query parameter that tells the route handler for the page you're redirecting to to look in the session to get the relevant data.
You could also create a temporary server-side cache of data. Generate a random key (likely a timestamp plus a random number). Store the data in a server-side Map using that key. Then put the key into a query string on the redirect. Then, in the route handler for the new, redirected page, it will see the query string parameter and it can grab that key out of the query string and access the data from the server-side Map serving as a temporary cache (and probably remove it from the cache too). This scheme works in a session-less environment.
You then need some scheme for cleaning up unused data from the cache so it doesn't accumulate. Probably what makes sense it to timestamp the data and then have a setInterval() timer that just removes things from the Map if their timestamp is older than xx minutes.
If the request is an Ajax call rather than a regular browser page request, then you don't need to use a redirect at all. You can just return the content that they would have gotten if they then followed your redirect. Then, you don't have to invent a temporary place to store the data. You can just use the data to generate the desired page and return it.
Store the data as session data and serve it back up to them when they land on the landing page.
Another way would be to have the client request the data asynchronously once the redirect has been performed.

download json file instead of console.log-ging it in $.getJson()

Is there a way I can download a json file instead of getting with jQuery's $.getJSON() and logging the callback function's argument, which is the json?
I don't want to manually type it from the console.log because it is long. Is there a way I can print it perhaps, and not formatted, so I can copy - paste it into a .json file?
I can't just go to the URL as I'm passing some json to the url as $.getJSON()'s second argument to access the response json.
try using
JSON.stringify(response);
There are also many websites and plugins that will let you make POST requests from your browser such as hurl.it or Postman (Chrome app).

Breeze.js: How to include all related data in payload even if it was sent

I have a list of of data being return from a "standard" HttpGet IQueryable method from an ApiController that implements the Breeze EFContextProvider. When one of the objects references another object that has already been returned in the payload, Breeze gives me an $ref to refer to the object that was already returned.
I want the object with all related objects return explicitly, not a reference with $ref. Also, I'm not using the breeze.js library on the client side; simply making straight calls to the Controller with a web address.
I found this:
Breeze does not replace the Ref: node with its real data
which is the thing I'm looking for, but using Include on the server still doesn't return all of the data.
Any idea on how to "force" Breeze on the server side to include all related data no matter if it was returned and referenced in the payload?
Update 1
Per Steve's answer below I added the following to the BreezeWebApiConfig.RegisterBreezePreStart method in the App_Start folder:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Object;
Compiling and running produces the same output with only the $ref group instead of the full data. I'm sending a request to the server to $expand the collection. Do I need to change the SerializerSettings upon each request to the controller or will adding this to the BreezeWebApiConfig.RegisterBreezePreStart method be enough?
Update 2
I've added a CustomBreezeConfig class per the instructions at the link that Steve added in his answer. I am however using Breeze.WebApi2 so it appears that the BreezeConfig is actually in Breeze.ContextProvider. The code compiles, but I'm still seeing the same $ref for the actual object in JSON.
Do I need to include this CustomerBreezeConfig class in a specific place in my project for Breeze to use it's serializer settings?
Under WebAPI, Breeze uses the Json.NET serializer to turn the results to JSON. You can change the serializer settings (specifically the PreserveObjectReferences setting) to change this behavior.
Breeze configures it's own JSON serializer, so in a Breeze app, you'll need to configure it as described in the Breeze Web API Controller doc.
Note that, if you turn PreserveObjectReferences off, you might also need to configure the ReferenceLoopHandling setting, if you have circular reference in your object graphs (as most of us do).

using backbone to put data into rest server

I have a question.
If i have a model named Input. It contains model Invoice and Collection InvoiceDetailCollection.
I modified the backbone.js specifically create:"POST" into create:"PUT" inorder to allow PUT since my service doesn't use POST.
If i were to use Input.save() What should my server expect as a request? I mean already have set a service method to expect string since if i expect string i can't use the input.save();
What should be the right parameter i should expect on my server side if i were to use the Input.save() method of backbone.js
By default, Backbone sends application/json data and the server should expects JSON data. You'll want to decode it. I use PHP and middleware that automatically json_decode($data) and turns it into an associative array for me to manipulate.
If this isn't possible, (can't take JSON data) I think what you want is to use emulateJSON It will serialize your data and send it as application/x-www-form-urlencoded like an HTML form.
http://documentcloud.github.com/backbone/#Sync-emulateJSON

YUI "Get" utility to parse JSON response?

The documentation page for the YUI "Get" utility says:
Get Utility is ideal for loading your
own scripts or CSS progressively
(lazy-loading) or for retrieving
cross-domain JSON data from sources in
which you have total trust.
...but doesn't have any actual examples for how to do so. Their one example doesn't actually request a JSON document from a remote server, but instead a document containing actual JavaScript along with the JSON data.
I'm just interested in the JSON response from the Google Maps API HTTP (REST) interface. Because I can't do cross-site scripting with the "Connect" utility, I am trying the "Get" utility. But merely inserting some JSON data into the page isn't going to do anything, of course. I have to assign it to a variable. But how?
Also, just inserting JSON data into the page makes Firefox complain that there's a JavaScript error. And understandably! Plain ol' JSON data isn't going to parse as valid JavaScript.
Any ideas?
Normally in this case the easiest thing to do is to return javascript that calls a callback with the json. For example:
function xdCallback( json ) {
// here I can do whatever I need with json, maybe
SomeModule.heresTheJson( json );
// or
globalVar.json = json;
// etc
}
And so on your server side you return not just JSON but instead something like:
xdCallback( { json: 'goes', here: true } );
...execute the 'script' when you get it via your ajax call and you're set.
OK. Looks like without Google's HTTP Geocoding interface supporting JSONP, there is no way to do this. :(
Sean -- You may find that YUI Connection Manager's XDR support is what you're looking for --
http://developer.yahoo.com/yui/examples/connection/xdr.html (YUI 2)
http://developer.yahoo.com/yui/3/examples/io/io-xdr.html (YUI 3)
Use Connection Manager (YUI 2) or IO (YUI 3) to bring in the JSON, and then use the JSON component in either codeline to parse the JSON once it's loaded.
If Google or Yahoo! has the necessary cross-domain support on the relevant servers, you should be in business.
-Eric
I have used YAHOO.lang.JSON.parse to parse a string to json. Also the stringify method can be used to go from JSON back to a string:
http://developer.yahoo.com/yui/docs/YAHOO.lang.JSON.html

Categories

Resources