Backbone.js binding collection to models after a fetch using ajax - backbone.js

I'm trying to learn backbone.js and I'm having trouble understanding how to bind models and read them after a fetch.
This is my code:
$(function() {
var Bid = Backbone.Model.extend();
var BidsList = Backbone.Collection.extend({
model: Bid,
url: '/buyers/auction/latestBids?auctionId=26&latestBidId=0',
});
var BidsView = Backbone.View.extend({
el: $('#bids'),
initialize: function() {
log('hi');
_.bindAll(this, 'render');
this.collection = new BidsList();
this.collection.fetch();
this.render();
},
render: function() {
log(this.collection);
return this;
},
});
var bidsView = new BidsView();
});
function log(m) { console.log(m); }
This is what the webservice json looks like
{
"AuctionState":3,
"ClosedOn":null,
"Bids":[
{
"BidId":132,
"AuctionId":26
},
{
"BidId":131,
"AuctionId":2
}
]
}
How do I would I bind that response to the model?

You need to override the parse() method on your BidCollection to pull the Bids out and present them, and them only, to the collection's add() routine. You can do other things with the parse() method to manage the AuctionState field.
You also need to listen for 'change' events in your view, so the view automatically updates after the fetch. You shouldn't need to call render() in your view; you should bind the model's 'change' event to to render(), then fetch the data and let that trigger the render.
As always, Backbone's source code is highly readable. I recommend learning and understanding it.
For example:
var BidsList = Backbone.Collection.extend({
model: Bid,
url: '/buyers/auction/latestBids?auctionId=26&latestBidId=0',
parse: function(response){
return response.Bids;
}
});

Related

unable to call fetch on a backbone model

In the function jsonRequest below, I can log this.model to the console, but I can't call this.model.fetch(), which I thought was the appropriate way to make a request to my server (at localhost:8080/jsonapi). The error it gives me is can't call fetch of undefined. Is there something I'm doing wrong in the code below?
var MyModel = Backbone.Model.extend({
url: 'jsonapi',
});
var MyView = Backbone.View.extend({
el: '#blahblah',
initialize: function(){
},
events: {
'click #start' : 'callJsonRequest',
},
callJsonRequest: function(){
setInterval(this.jsonRequest, 1000);
},
jsonRequest: function(){
console.log("jsonrequest", this.model); //this logs the model
this.model.fetch();
},
});
window.myModel = new MyModel();
window.startStop = new StartView({model: myModel});
You likely need to use bind to make sure this is the context of your View object.
As you mentioned in the comments, you can do:
setInterval(this.jsonRequest.bind(this), 1000);

Backbone localstorage A "url" property or function must be specified

I am creating a small application based on a backbone example with the backbone-localstorage plugin.
When saving the data for a new model I always get the error "A "url" property or function must be specified"
After reading through several simular topics I'm still not able to find the cause for this.
Model:
directory.models.EmployeeCollection = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("EmployeeCollection"),
model: directory.models.Employee,
store: directory.utils.store,
findByName: function(key) {
this.reset(this.store.findByName(key));
}
});
The view:
directory.views.newEmployeeView = Backbone.View.extend({
tagName: "div",
initialize: function() {
this.template = _.template(directory.utils.templateLoader.get('new-employee'));
},
events: {
"click .save": "saveEmployee"
},
render: function(eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
saveEmployee: function(event){
this.model.set({
firstName:$('#newFirstName').val(),
lastName:$('#newLastName').val(),
title:$('#newTitle').val(),
city:$('#newCity').val(),
officePhone:$('#newOfficePhone').val(),
cellPhone:$('#newCellPhone').val(),
email:$('#newEmail').val()
});
this.model.save();
window.history.back();
return false;
}
});
I think you need the new model to be a member of your collection before you attempt to persist it. Try creating a new instance of your collection and passing it to the view (probably in your router) like this:
new newEmployeeView({ collection: new EmployeeCollection() });
In your view you can use Backbone's create convenience method (see docs) to add a new instance of the model to the collection and persist it:
this.collection.create({
firstName:$('#newFirstName').val(),
lastName:$('#newLastName').val(),
title:$('#newTitle').val(),
city:$('#newCity').val(),
officePhone:$('#newOfficePhone').val(),
cellPhone:$('#newCellPhone').val(),
email:$('#newEmail').val()
});

How to retrieve an object from Parse.com after saving it

I'm creating an application for Phonegap using Backbone framework and Parse.com as backend service. I create an object with Parse.com (corresponding to Backbone models).
This object has a saveDraftToP() method that calls the Parse.com function save().
After this method is called from a view, I'd like to retrieve the updated object.
To do so I'm binding the 'change' event to the model but the Parse assigned ID is undefined.
Here is the code of the model:
var Match = Parse.Object.extend("Match", {
states: {'DRAFT': 0, 'RUNNING': 1, 'ENDED': 2},
saveDraftToP: function () {
var self = this;
this.save({
user: Parse.User.current(),
ACL: new Parse.ACL(Parse.User.current()),
state: self.states.DRAFT
}, {
success: function (result) {
self = result;
},
error: function (e) {
}
});
}
});`
And here is the code for the view:
var vmNuovaPartita = Parse.View.extend({
template: Handlebars.compile(template),
model: new Match(),
collection: new HintCollection(),
initialize: function () {
this.bind("change:model", console.log(this.model.id) , this);
},
render: function (eventName) {
var match = this.model.toJSON();
$(this.el).html(this.template(match));
return this;
}
});
I'm not quite sure why you have a save function wrapped in another save-like function. :-)
Say you have something like myMatch which is an object.
Through your UI, a button click saves the object data. You can just use myMatch.save({attr:val, ...}) straight out of the box. Backbone (and Parse) by default are optimistic. That means, you it will set the values of the model with the expectation that persisting to the server will succeed.
Thus, you don't need to retrieve anything extra. You already have the model in it's most current state.
To have a model view that responds to these changes, I'd design the view a little differently.
var vmNuovaPartita = Parse.View.extend({
template: Handlebars.compile(template),
initialize: function () {
this.model.on('change', this.render);
},
render: function (eventName) {
var match = this.model.toJSON();
$(this.el).html(this.template(match));
return this;
}
});
var myView = new vmNuovaPartita({
model: myModel
});
I'd initialize the model outside of the view, then pass it in as an option when you generate a new view. When you pass a model in as an option, it's special and will be attached directly to the view ... view.model which you can refer inside your view code as this.model
In the init we place a listener on the model for change events, then fire off a rerender of the view. Or a nicer way to go about this sort of thing is to throw in the newer Backbone Events with the .listenTo() method.

backbone router and collection issue

I have a collection and I need to access a model in the collection when a route is fired:
App.Houses = Backbone.Collection.extend({
model: App.House,
url: API_URL,
})
App.houseCollection = new App.Houses()
App.houseCollection.fetch();
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
model = App.houseCollection.get(id);
console.log(model);
App.Events.trigger('show_house', model);
},
});
The result of that console.log(model) is undefined. I think that this is the case because the collection has not finished the fetch() call?
I want to attach the model to the event that I am firing so that the views that respond to the event can utilize it. I might be taking a bad approach, I am not sure.
One of the views that responds to the event:
App.HouseDetailView = Backbone.View.extend({
el: '.house-details-area',
initialize: function() {
this.template = _.template($('#house-details-template').html());
App.Events.on('show_house', this.render, this);
App.Events.on('show_main_view', this.hide, this);
},
events: {
'click .btn-close': 'hide',
},
render: function(model) {
var html = this.template({model:model.toJSON()});
$(this.el).html(html);
$(this.el).show();
},
hide: function() {
$(this.el).hide();
App.detailsRouter.navigate('/', true);
}
});
EDIT: Somewhat hacky fix: See details()
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
if (App.houseCollection.models.length === 0) {
// if we are browsing to website.com/#details/:id
// directly, and the collection has not finished fetch(),
// we fetch the model.
model = new App.House();
model.id = id;
model.fetch({
success: function(data) {
App.Events.trigger('show_house', data);
}
});
} else {
// if we are getting to website.com/#details after browsing
// to website.com, the collection is already populated.
model = App.houseCollection.get(id);
App.Events.trigger('show_house', model);
}
},
});
Since you are using neither the callbacks nor events to know when the collection's fetch call completes, perhaps fetching the collection is generating an error, or the model you want is not included in the server response, or you are routing to the view before fetch has completed.
As to your approach, here are some miscellaneous tips:
better to pass the model to the view in the view's constructor's options parameter. render() takes no arguments and I think it is unconventional to change that.
Always return this from render() in your views
You can move your this.template = _.template code to the object literal you pass to extend. This code only needs to be run once per app load, not for each individual view
For now the simplest thing may be to instantiate just a model and a view inside your details route function, call fetch on the specific model of interest, and use the success callback to know when to render the view.

How to trigger the fetch method and how to set the url

I'am redesigning my backbone application based on the answer of #20100 to this question The best way to fetch and render a collection for a given object_id.
Please read the comment on the code because I think is more clear, and my question looks better in smaller sizes.
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (MyCollection, MyModel) {
var MyView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new MyCollection();
this.collection.on('add', this.onAddOne, this);
this.collection.on('reset', this.onAddAll, this);
// when I make myView = new MyView(_.extend( {el:this.$("#myView")} , this.options));
// myView.render is not called
// in order to trigger the render function I make the following… but probably there is a better way …
var that = this;
this.collection.fetch({
success: function () {
that.render();
}
});
}
});
return MyView;
});
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.MyCollection.extend({
model: MyModel, // add this
url: function () {
var url = "http://localhost/movies";
return url;
// if I look to the GET request the url is without idAttribute
// how can I attach the idAttribute to this url?
// should bb takes care of this?
}
});
return MyCollection;
});
//MyModel
define([
], function () {
var MyModel = Backbone.MyModel.extend({
idAttribute: 'object_id'
});
return MyModel
});
There's two paths you want to explore
Pre-populate your collection with your model data
In your example you're already doing this, but you're fetching a collection, the collection URL is http://localhost/movies, if you want an individual model take a look at the next point
Fetch each individual model only when you need it
In the assumption that you're trying to get an ID on a collection that is not pre-populated and are loading 1 model at a time, you will have to approach this a bit in a custom way by adding a method to your collection somewhat similarly to this
getOrFetch: function(id, options)
{
var model;
if (this.get(id))
{
model = this.get(id);
}
else
{
model = new this.model({
id: id
});
this.add(model);
model.fetch(options);
}
return model;
}
or add the function as Backbone.Collection.prototype.getOrFetch so you can use it on every Backbone Collection if you need it.

Resources