Using Backbone.js I need to handle an array of strings returned from a JSON web service. Should I create a Backbone Collection to fetch this list? Here is the data I get from the web service:
["Question Designer","Adaptive Question Designer","Clickable image map","Essay","Fill in the blanks","Maple-graded","Matching","Mathematical formula","Multipart question","Multiple choice","Multiple selection","Numeric","Palette-based symbolic editor","True/false","Other"]
I've created this simple Collection to fetch the data:
var questionTypesCollection = Backbone.Collection.extend({
url: function() {
return apiBase + '/questions/types';
}
});
But when I try to fetch() the collection, I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for 'id' in Question Designer
It looks like Backbone is trying to parse the strings as a model instead of seeing that it's just a raw string. How can I get the data into a Collection so I can use it in a View?
If you just need the strings, your best bet might be to just let jQuery (or Zepto--whatever has the $) handle the heavy lifting:
var names = [];
$.get(apiBase + '/questions/types', {}, function(result){
names = result;
})
After the fetch completes, the names variable will be populated with the results of your query.
This doesn't make a lot of sense, since backbone collection is designed to be, well, a collection of models.
However, you could override the parse method with your own parser.
Related
I am very new in backbone js.
I am trying to filter some specific key and values in backbone js model extend here is the code below.
var items = ["open","close"];
var ReportModel = Backbone.Model.extend({
url: function() {
return tab+".json";
}
});
where tabe is dynamic json file name.In my json file many key value pair are there but I want to load only those key which is mentioned in items list.
I saw some where using parse function but that a;so did not work out.Please do let me know how to filter the specific keys form json using the backbone.
I also tried creating a dict from json and pass it to model like.
var ReportModel = Backbone.Model.extend({
"open":{.......}
});
but there I am getting issue.
throw new Error('A "url" property or function must be specified');
Please help me out with this.
You are missing some steps to be succesfull on your task.
First a note about the error: Backbone expects a string on the url property while you're passing a function. If you want to use a function to return your url dinamically use urlRoot.
Now onto the real coding:
since you talk about a json file that has multiple key value, maybe you should declare your model as a key-value object, and then create a Backbone.Collection that will wrap your models.
A Backbone.Collection expose a lot of utilities that can help us modeling the results, in this case by using the where() function of our collection you will be able to filter the data after you have retrieved from the remote file.
Alternatively to filter your collection if you need more control over the function you can always call the undescore function filter() .
Please refer to the official documentation of underscore and backbone, as you will find a lot of functions that can help you and most of them have an example that shows how to use them.
Now that we have everything lets create our Backbone.Collection that will wrap your already defined model:
var ReportCollection = Backbone.Collection.extend({
model: ReportModel,
urlRoot: function(){
return 'yoururl.json';
}
});
now if you want to filter the result you can simply fetch the collection and perform a filter on it:
var myReports = new ReportCollection();
//call the fetch method to retrieve the information from remote
myReports.fetch({success: function(){
//the collection has been fetched correctly, call the native where function with the key to be used as a filter.
var filteredElements = myReports.where({my_filter_key : my_filter_value});
});
in your filteredElements you will have an array of object made up of all the model that matched the key/value passed to the where function.
If you need a new Collection from that you just need to pass the result as argument: var filteredCollection = new ReportCollection(filteredElements);
You can use _.pick() in the parse method as shown below:
var items = ["open", "close"];
var ReportModel = Backbone.Model.extend({
url: function() {
return tab + ".json";
},
parse: function(response) {
return _.pick(response, items);
}
});
In backbone javascript models, we get individual items as shown below:
var type = this.model.get("type");
Here, type will be defined in server side & then fetched in JS using above syntax.
My question is how do I get the entire model in one shot?
I tried this.model.toString() but it prints [object object]
Any suggestion?
EDIT: I'm using above line of code in backbone view & not the model. And in this view, I need to read all the models data even if its JSON string, thts fine with me. How do I get it. I don't want to use separate collection or anything else. I need to update the above view only to get entire model.
You can use model.toJSON() to get all the attributes of a model.
you use a collection
http://backbonejs.org/#Collection
You can then iterate though the collection to obtain each model.
var Library = Backbone.Collection.extend({
model: Book
});
for example and then
books = new Library();
books.each(function(book) {
book.publish();
});
to iterate
I'm currently going through a backbone.js tutorial and instead of using the suggested REST service I'm using one from my company as a real-world example. The problem is that the tutorial uses a very simple JSON return from the REST server like this:
{
"name":"Brian"
"age":52
},
"name":"Mary"
"age":"27"
}
... etc.
My own data contains arrays of this type:
{
"records":20,
"customers": [{name:"Simon", age:27},{name:"Mary", age:28}... etc.]
}
I want to get at 'customers' in this case. I believe I can use parse: within a Model for this but this tutorial uses only a Collection and renders that out to the template. Can I do this with just a Collection? Or should I make a Model and use parse:?
You can use a collection -- just override Collection.parse. This is the function that Backbone calls to convert the raw AJAX response into model attributes. In your case, you just need it to return response.customers instead of the raw response:
var MyCollection = Backbone.Collection.extend({
parse: function(response) {
return response.customers;
}
});
I have read and read the docs on these two methods, but for the life of me cannot work out why you might use one over the other?
Could someone just give me a basic code situation where one would be application and the other wouldn't.
reset sets the collection with an array of models that you specify:
collection.reset( [ { name: "model1" }, { name: "model2" } ] );
fetch retrieves the collection data from the server, using the URL you've specified for the collection.
collection.fetch( { url: someUrl, success: function(collection) {
// collection has values from someUrl
} } );
Here's a Fiddle illustrating the difference.
We're assuming here that you've read the documentation, else it'l be a little confusing here.
If you look at documentation of fetch and reset, what it says is, suppose you have specified the url property of the collection - which might be pointing to some server code, and should return a json array of models, and you want the collection to be filled with the models being returned, you will use fetch.
For example you have the following json being returned from the server on the collection url:
[{
id : 1,
name : "a"
}, {
id : 2,
name : "b"
}, {
id : 3,
name : "c"
}]
Which will create 3 models in your collection after successful fetch. If you hunt for the code of collection fetch here you will see that fetch will get the response and internally will call either reset or add based on options specified.
So, coming back to discussion, reset assumes that we already have json of models, which we want to be stored in collection, we will pass it as a parameter to it. In your life, ever if you want to update the collection and you already have the models on client side, then you don't need to use fetch, reset will do your job.
Hence, if you want to the same json to be filled in the collection with the help of reset you can do something like this:
var _self = this;
$.getJSON("url", function(response) {
_self.reset(response); // assuming response returns the same json as above
});
Well, this is not a practice to be followed, for this scenario fetch is better, its just used for example.
Another example of reset is on the documentation page.
Hope it gives a little bit of idea and makes your life better :)
reset() is used for replacing collection with new array. For example:
#collection.reset(#full_collection.models)
would load #full_collections models, however
#collection.reset()
would return empty collection.
And fetch() function returns default collection of model
I have a situation using backbone.js where I have a collection of models, and some additional information about the models. For example, imagine that I'm returning a list of amounts: they have a quantity associated with each model. Assume now that the unit for each of the amounts is always the same: say quarts. Then the json object I get back from my service might be something like:
{
dataPoints: [
{quantity: 5 },
{quantity: 10 },
...
],
unit : quarts
}
Now backbone collections have no real mechanism for natively associating this meta-data with the collection, but it was suggested to me in this question: Setting attributes on a collection - backbone js that I can extend the collection with a .meta(property, [value]) style function - which is a great solution. However, naturally it follows that we'd like to be able to cleanly retrieve this data from a json response like the one we have above.
Backbone.js gives us the parse(response) function, which allows us to specify where to extract the collection's list of models from in combination with the url attribute. There is no way that I'm aware of, however, to make a more intelligent function without overloading fetch() which would remove the partial functionality that is already available.
My question is this: is there a better option than overloading fetch() (and trying it to call it's superclass implementation) to achieve what I want to achieve?
Thanks
Personally, I would wrap the Collection inside another Model, and then override parse, like so:
var DataPointsCollection = Backbone.Collection.extend({ /* etc etc */ });
var CollectionContainer = Backbone.Model.extend({
defaults: {
dataPoints: new DataPointsCollection(),
unit: "quarts"
},
parse: function(obj) {
// update the inner collection
this.get("dataPoints").refresh(obj.dataPoints);
// this mightn't be necessary
delete obj.dataPoints;
return obj;
}
});
The Collection.refresh() call updates the model with new values. Passing in a custom meta value to the Collection as previously suggested might stop you from being able to bind to those meta values.
This meta data does not belong on the collection. It belongs in the name or some other descriptor of the code. Your code should declaratively know that the collection it has is only full of quartz elements. It already does since the url points to quartz elements.
var quartzCollection = new FooCollection();
quartzCollection.url = quartzurl;
quartzCollection.fetch();
If you really need to get this data why don't you just call
_.uniq(quartzCollecion.pluck("unit"))[0];