Goodmorning,i'm a bit confused about a specific id that a model has got and the id that it's has in parse.com because my collection is linked to parse.com.
If i want to get a specific model from my collection how can i do?
An example,my collection is this:
var Proposte = Backbone.Collection.extend({
model:Proposta,
url:'https://api.parse.com/1/classes/Proposte',
});
return Proposte;
and my model is this:
var Proposta = Backbone.Model.extend({
url:"https://api.parse.com/1/classes/Proposte",
...
If i want to get a specific model from my collection how can i do?
have a try at this:
var item = Proposte.findWhere({'url':"https://api.parse.com/1/classes/Proposte"});
hare is the doc
Edit:
The code above gives you the first matched model of the collection.
If you want to get multiple models that matches the specific attributes of a model, just use where
General case:
Define idAttribute for your Model/Collection:
var Proposta = Backbone.Model.extend({
idAttribute: 'name',
});
var Proposte = Backbone.Collection.extend({
model:Proposta,
url:'https://api.parse.com/1/classes/Proposte'
});
// Done here with static data just for illustration
var collection = new Proposte([{name: 'aaa'}, {name: 'bbb'}]);
Use the defined attribute to retrieve Models from collection:
console.log(collection.get('aaa'));
JSFIddle
URL, of course, can also be that attribute (just in case):
var Proposta = Backbone.Model.extend({
idAttribute: 'url'
});
var Proposte = Backbone.Collection.extend({
model:Proposta,
url:'https://api.parse.com/1/classes/Proposte',
});
var collection = new Proposte([{url: 'https://api.parse.com/1/classes/Proposte/1'}, {url: 'https://api.parse.com/1/classes/Proposte/2'}]);
console.log(collection.get('https://api.parse.com/1/classes/Proposte/2'));
Related
I made a website to create some maps. So, all my maps have an id, and my map has some elements with ids.
So I create a collection Map with an id and its model is my map object :
app.collections.mapDetailsCollection = Backbone.Collection.extend({
model: app.models.mapDetailsModel,
initialize: function(options) {
this.id = options.id;
},
url: function () {
return this.absURL + '/api/maps/' + this.id;
},
parse: function(response){
return response.features;
},
toGeoJSON: function(){
var features = [];
this.models.forEach(function(model){
var feature = model.toGeoJSON();
if (! _.isEmpty(feature.geometry)) {
features.push(feature);
}
});
return {
'type': 'FeatureCollection',
'features': features
};
}
});
But my model have an id too. I don't know for a model how to return url with a collection id.
I need to return /api/maps/id_collection/id_model.
When a model is added to a collection, it receives a reference to the collection. So each model has a collection property this.collection set if it's in a collection.
From the Backbone model constructor documentation (emphasis mine):
If you pass a {collection: ...} as the options, the model gains a
collection property that will be used to indicate which collection the
model belongs to, and is used to help compute the model's url. The
model.collection property is normally created automatically when you
first add a model to a collection. Note that the reverse is not true,
as passing this option to the constructor will not automatically add
the model to the collection. Useful, sometimes.
Then, you could use that to build the full url of a model:
var app.models.mapDetailsModel = Backbone.Model.extend({
urlRoot: function() {
// Backbone adds the model id automatically
return this.collection.url() + '/my-model/';
}
// ...snip...
});
Note that the default url for a model is what you want.
Generates URLs of the form: [collection.url]/[id] by default, but
you may override by specifying an explicit urlRoot if the model's
collection shouldn't be taken into account.
I have the following Backbone Model and Collection
/**
* DataPoint
*/
var DataPoint = Backbone.Model.extend({
defaults: {
ts: null,
value: null
}
});
var DataPointCollection = Backbone.Collection.extend({
model: DataPoint
});
In order to populate and do what I need to do with the data I do something similar to this:
url = '/api/v1/database/1/data';
$.getJSON(url, params, function(data) {
var dps = new DataPointCollection;
dps.add(data.datapoints);
//Now do stuff with dps
});
I'm sure there is a better way to do this with Backbone but not sure how. I feel it should be more like telling the DataPoint collection to populate itself.
How to approach this on backbone?
Have a look at the docs, fetch is what you're looking for; here's the example took from there:
var accounts = new Backbone.Collection;
accounts.url = '/accounts';
accounts.fetch();
i'm trying to populate a nested collection that's inside a model, and taht last model inside another collection.
The code is the following
App.Models.Bed = Backbone.Model.extend();
App.Collections.Beds = Backbone.Collection.extend({
model: App.Models.Bed,
initialize: function(models, options){
this.room = options.room;
}
});
App.Models.Room = Backbone.Model.extend();
App.Collections.Room = Backbone.Collection.extend({
url: 'rooms/',
initialize: function(){
this.on('reset', this.getBeds, this);
},
getBeds: function(){
this.each(function( room ){
room.beds = new App.Collections.Beds([], { room: room});
room.beds.url = 'rooms/' + room.id + '/beds';
room.beds.fetch();
console.log(room.beds.toJSON());
});
}
});
Now, if I execute:
var rooms = new App.Collections.Room();
rooms.fetch();
rooms.toJSON();
It gives me back just the rooms populated, but no beds property on each bed.
The wired thing is that it makes the request to the server at /rooms/1/beds and I get back each bed.
Is it populating the beds collection?
Am I doing something wrong?
Thanks for your time mates.
Looks like you need to pass in the Room Model to the Room Collections.
Have an array of id's
['tom','tim','joe','matt','scott']
Each model has an attribute that has an id.
How can I grab all 5 of the models and put in a new collection?
How about using the underscore filter method on the corresponding collection?
var ids = ['tom','tim','joe','matt','scott'];
var matches = collection.filter(function (model) {
return ids.indexOf(model.id) > -1;
});
If you need to fetch the models from your persistence layer, you might consider generating a collection of models with the id attribute set and providing an appropriate endpoint to populate the other attributes:
var MyCollection = Backbone.Collection.extend({
model: MyModel, // whatever your model is
url: '/byname' // whatever the endpoint is
});
var models = [];
_.each(ids, function (id) {
models.push({ id: id });
});
var collection = new MyCollection;
collection.fetch({ models: models }); // fetch the associated models
Whatever endpoint you provide (/byname in the example above) should be prepared to generate a collection containing each model whose id was specified in the models parameter.
I have a Clock model in Backbone:
var Clock = Backbone.Model.extend({});
I'm trying to get an instance of that that has the latest information from /clocks/123. Some things I've tried:
a "class"-level method
Clock.fetch(123)
// TypeError: Object function (){ ... } has no method 'fetch'
creating an instance and then calling fetch on it:
c = new Clock({id: 123})
c.fetch()
// Error: A 'url' property or function must be specified
a collection
I tried creating an AllClocks collection resource (even though I have no use for such a thing on the page):
var AllClocks = Backbone.Collection.extend({
model: Clock,
url: '/clocks/'
});
var allClocks = new AllClocks();
allClocks.fetch(123);
// returns everything from /clocks/
How do I just get one API-backed Clock?
Try specifying urlRoot in the model:
From the docs:
var Book = Backbone.Model.extend({urlRoot : '/books'});
var solaris = new Book({id: "1083-lem-solaris"});
solaris.fetch();
Your second approach is the approach I have used. Try adding the following to your Clock model:
url : function() {
var base = 'clocks';
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
This approach assumes that you have implemented controllers with the hashbang in your URL like so, http://www.mydomain.com/#clocks/123 , but it should work even if you haven't yet.
I personally recommend, following the Model#url method documentation
model = new Model(id: 1)
view = new View(model: model)
collection = new Collection([model])
model.fetch()
in your collection remember to add the collection url:
url: "/models"
and in your View's initialize function do:
this.model.bind("change", this.render)
this way backbone will do an ajax request using this url:
"/models/1"
your model will be updated and the view rendered, without modifying Collection#url or Model#urlRoot
note:
sorry this example came out in coffee script, but you can easily translate it to js adding var statements
var Person = Backbone.Model.extend({urlRoot : '/person/details'});
var myName = new Person({id: "12345"});
myName.fetch();
As a result you make a Ajax request on the
URL http://[domainName]/person/details/id
and you have the JSON response back.
Enjoiiii !!!
...and do this if you don't want the trailing slash on the model urlRoot:
url : function() {
return this.urlRoot + this.id;
},
You probably should be accessing the object trough a collection and keeping it in the collection all the time. This is how to do it:
var AllClocks = Backbone.Collection.extend({
model: Clock,
url: '/clocks/'
});
var allClocks = new AllClocks();
my_clock = allClocks.add({id: 123});
my_clock.fetch()
I want to use RESTful url,but I couldn't understand why 'postId' can't be added to base url.
var PostModel = Backbone.Model.extend({
urlRoot: 'getBlogPost',
defaults: {
postTitle: "defaultTitle",
postTime: "1970-01-01",
postContent: "defaultContent",
postAuthor: "anonymous"
}
});
var post = new PostModel({
postId: 1
});
alert(post.url());
Then I know only after I set 'idAttribute' as 'postId' in Model can I get the right url.
like this:
var PostModel = Backbone.Model.extend({
idAttribute: 'postId',
urlRoot: 'getBlogPost',
defaults: {
postTitle: "defaultTitle",
postTime: "1970-01-01",
postContent: "defaultContent",
postAuthor: "anonymous"
}
});