I'm trying to learn to fetch data from a database using the Backbone.js Collection method: fetch().
The jsfiddle example is here.
The object's length returned is zero which means I'm not getting any result back. I can very easily obtain the json using jquery ajax and Backbone.sync is apparently using the .ajax method too. May I know what's wrong?
You're running across two issues.
The first is that twitter's results (what you want to turn into backbone models) resides under a "results" property. To use this data, you need to override the parse method in the collection. This is the specific example used in the backbone docs:
http://documentcloud.github.com/backbone/#Collection-parse
The second issue is that the fetch() method is asynchronous, so that when you're getting the 'length' on the collection, its happening before the response comes back from twitter, so its still 0 length.
You need to set up an event handler to listen for the results of the "fetch" and THEN output the length:
var Tweet = Backbone.Model.extend();
var Tweets = Backbone.Collection.extend({
model: Tweet,
url: 'http://search.twitter.com/search.json?q=obama&callback=?',
parse: function(response) {
return response.results;
}
});
var tweets = new Tweets();
tweets.bind('reset', function(collection) {
alert(collection.length);
});
tweets.fetch();
Related
I am learning backbone.js. I am using firebase for API. I can't able to display data. Can anyone help me please?
I follow instruction mention on https://github.com/firebase/backbonefire.
var realtimeList = new RealtimeList();
realtimeList.on('sync', function(collection) {
console.log('collection is loaded ', collection);
// todoView.render();
});
Collection is object.
DEMO
Your view element is not part of DOM. You need to add it to DOM. I've used el property to do so for the sake of demo.
Also you need to stringify the JavaScript object returned by toJSON() to display in DOM.
Updated demo.
Your API is returning empty collection at the moment so I've used the todoItem model created locally for demo. But it isn't part of the Firebase collection. You need to pass the collection to view and render the models inside it in order to view realtime data.
I have this ASP.NET User Control that (as a part of its rendering phase) needs to execute some javascript at client-side. I use ScriptManager.RegisterStartupScript to register the script I want to execute when response reaches the client. Now, in my scenario my control is contained inside an Update panel (to be more precise, it is ajaxified using a Telerik RadAjaxManager). On the same page, I have a second Update panel (again to be more precise, a second panel ajaxified with a second RadAjaxManager setting). When this second panel raises a partial postback, I expect the changes (including any emitted script) from my control to be ignored. This is not the case and frustratingly, I cannot determine what to do? Any ideas ?
IDEA #1: Stop using UpdatePanel.
ASP Webforms are great for a lot of things...partial page rendering is not one of them. While the UpdatePanel does technically perform "partial page-rendering", it also performs a full postback.
Instead, use this alternative . . .
Create an ASP Web API and regain control over your page loading process. By creating a web API controller (which is pretty much just a function on the server that you can call using javascript) you can pass to the server specific information, run only the function (or functions) necessary for the action you are performing, and then return the exact data you need to display on your client.
The same javascript function that makes the call to the server (i.e., your ASP Web API controller) will also handle the response returned, which is easily formatted in the always-simple-to-use JSON format. In the end, your javascript would look something like this:
$('.show-kitten-button').click(function () { // this binds the click event whatever button begins the action.
// then we'll store some values in our variables
var kittenType = $('input.kitten-type').val(); // "calico" ...from asp textbox with a CssClass="kitten-type" attribute.
});
// function to make the call to the ASP Web API controller.
function getKittenPicture(kittenType) {
$.ajax({ // jQuery's AJAX function works well
type: "GET" // there are four types of requests: get, post, update, and delete. You can do most actions with get and post.
, url: 'http://yourWebSite.com/api/kittens/' + kittenType // the URL that routes to your ASP Web API controller. This is specified in the global.asax file.
, success: function (data) { // handle the data if the HTTP response indicates success
if (data || false) { // if data exists
var jsonData = JSON.parse(data); // parse it as JSON. This is assuming you are returning a serialized class object from C# or VB.NET. See below for more info on this.
var kittenImageSrcUrl = jsonData.src; // grab the data from the JSON object.
showKittenImage(kittenImageSrcUrl); // run the function to show the kitten image.
}
}
, error: function (data) { // handle the data if the HTTP response indicates an error.
console.log('An error occurred while retrieving the cute kitten picture.');
console.log('Error response: ', JSON.parse(data.responseJSON));
}
, complete: function (data) {
// any code to perform once the success (or error) function is complete.
}
});
};
function showKittenImage(imgSrc) { // function to show cute kitten image
$("#kittenImage").attr("src", "kittenImageSrcUrl"); // change the src attribute of the image to match the src URL we got back from the server.
};
More info
If you haven't yet dabbled in the world of APIs, then you're in for a real treat, because it is much, much easier and more effective than using UpdatePanels. UpdatePanels seem simple at first glance--there's not much to making one and they do give the appearance of dynamic page content--but once you start adding multiple panels, inserting start-up scripts, etc...it gets hairy very quickly. Below here are links to everything you'll need to build your first API. I encourage you to check them out...
Chad Carter's tutorial on how to implement ASP Web API in Webforms. (VB)
Microsoft's tutorial on how to use ASP Web API with Webforms. (C#)
Making POST requests to ASP Web API with multiple parameters.
Using jQuery to POST parameters from body. (VB & C#)
I am using ASP.NET MVC AJAX with the #AJAX.ActionLink helper to implement item deletion from a grid. When the request is executed it returns the grid without the deleted item and the AJAX helpers replace the grid. This works just fine but the problem is what to do if the item cannot be deleted (in my case due to foreign key constraints). How can I report the error to the client and display appropriate message. I don't want to use the OnFailure function blindly because I don't want to show the same error message for all errors. Ideally there will be a way to send specific error from the action and inspect the error in the JavaScript OnFailure function but I can't seem to find it.
Of course I can downgrade to returning JSON, manually executing AJAX calls and replacing UI elements but I don't really feel like it. I'd rather do something dirty like render a hidden input with the error information and check for it on the client but I don't want to do that either if there is better way.
You can return status code and error message from the controller and pass it to the ajax OnFailure function
return new HttpStatusCodeResult(HttpStatusCode.Conflict, "The entity is currently used");
as shown here: ASP.NET MVC AJAX onError handling
and in the client side JS:
function deleteFailure(responce) {
var statusCode = responce.status;
var responceText = responce.statusText;
if(statusCode == 409){
//do something specific for specific errors
}
alert(responceText);
}
i'd like to fetch a bunch of models via a collection by a list of model IDs. My problem is that i have to fetch dozens of models at once. I don't want to put dozens over douzens of IDs into the URL when firing a GET request.
I'm thinking about a POST request. But can this be done via Collection?
Maybe this way: https://gist.github.com/2953670
I know i'm raping a POST/create request. Alternatively i have jQuery.post() in mind.
What is the better way?
Thanks in advance,
JW
Everytime a model/collection does a sync call, it actually does return (this.sync || Backbone.sync).call.... This allows you to implement a custom sync for a specific model or collection.
var Equipment.Collection = Backbone.Collection.extend({
...
"sync": urSync,
...
});
I'm trying to populate a Dojo grid with data from an ASP.Net web service. There is going to be a lot of rows, so I want to implement paging on the server side, so the web service will accept parameters "start" and "count". I've gotten pretty close, by using QueryReadStore and overriding the "fetch" function to add additional parameters (the web service requires more than just start and count).
The immediate problem I've encountered is that the web service is returning the data as XML. I believe this is because the request does not contain a Content-Type header indicating a preference for json (which the grid wants). I am using an Http-Post rather than the default Get. Is a ResponseFormat attribute supposed to override this? It doesn't work for me.
So, how do I get the data as json? Or alternately, am I barking up the wrong tree? It would seem like a pretty common thing to glue together a grid and a web service. Does Dojo have any built-in functionality for this that I am just not aware of?
Thanks
You should be able to simply set the handleAs parameter on your call to dojo.xhrPost(..) to "xml", this will bind the XML to javascript objects to make your life easier while handling the data:
dojo.xhrPost({
url: "http://whatever.com/someendpoint",
handleAs: "xml",
load: function(response, ioArgs){
/*
* Do something with response, it's a JS object that reflects the XML.
*/
}
});
Alternatively, you could chose to send different HTTP Headers in your AJAX call by using the headers property of the argument object for dojo.xhrPost(..):
dojo.xhrPost({
url: "http://whatever.com/someendpoint",
handleAs: "json",
headers: {
"Accept" : "text/javascript, text/json, application/json, application/javascript"
},
load: function(response, ioArgs){
/*
* Do something with response, it's a JS object that reflects the JSON.
*/
}
});