var elementUrlRoot = api_url + '/elements';
var elementModel = Backbone.Model.extend({
'idAttribute': '_id' //mongoDB
, 'urlRoot': elementUrlRoot
, defaults: {
"signature": "",
"group": 0
}//defaults
});
var elementCollection = Backbone.Collection.extend({
model: elementModel
, 'url': elementUrlRoot
});
var testmodel = new elementModel({DOM_id: 111});
testmodel.save({signature: "test"},
{
error: function (model, response, options) {
console.log('test model save error:', response);
},
success: function () {
console.log('test model save success');
}
}
);
My backbone model is not saved to the server when I update it.
I have set the urlRoot attribute of the Model (which according to the documentation should not be necessary). But there are still no HTTP requests being issued.
Update:
I have added a success method in the callback. It is being executed.
But there are no requests being sent to the server.
Update:
I found the error. I had added this code to save a whole collection.
Backbone.Collection.prototype.syncCollection = function (options) {
console.log('syncing the collection');
Backbone.sync("create", this, options);
};
It worked and I was able to save collections with it.
But it seems to have caused a problem with saving individual models. Requests are issued when I removed it.
Your urlRoot is needed because your model is not part of a collection.
Try unquoting your urlRoot attribute on the left side of the assignment
http://backbonejs.org/#Model-urlRoot
Related
I seem to be fetching correctly from the server using backbone. A GET request is made to a MongDB collection, via the Node.js server code here:
exports.getTeams = function(req,res,next){
var system_db = req.system_db;
var user_id = req.mainUser._id;
var teams = teamModel.getNewTeam(system_db,user_id);
teams.find({}, function (err, items) {
res.json(items);
});
};
I am fetching from Backbone like so:
var teamCollection = new TeamCollection([]);
teamCollection.url = '/api/teams';
teamCollection.fetch(
{success:function(){
console.log('teamCollection length:',teamCollection.length);
console.log('teamCollection[0]:',teamCollection[0]);
}}
);
using this model and collection:
var Team = Backbone.Model.extend({
idAttribute: "_id",
urlRoot: 'http://localhost:3000/api/teams'
});
var TeamCollection = Backbone.Collection.extend({
model: Team,
initialize: function() {
this.bind('add', this.onModelAdded, this);
this.bind('remove', this.onModelRemoved, this);
this.bind("change", this.onModelChanged, this);
},
/* parse: function(data) {
//return JSON.stringify(data).objects;
//return JSON.parse(data).objects;
return data.objects;
},*/
onModelAdded: function(model, collection, options) {
console.log("added, options:", options);
},
onModelRemoved: function (model, collection, options) {
console.log("removed, options:", options);
},
onModelChanged: function (model, collection, options) {
console.log('Collection has changed.');
},
comparator: function (model) {
return model.get("_id");
}
});
the problem is that the logging statements above log the following in the browser console:
It says I am sending 4 items from the server to the Backbone client, but the first one is undefined. How could this be?
A Backbone.Collection is not an array-like object : it has a length attribute representing the number of models but you can't access individual models via indexes, hence
console.log(teamCollection[0]); //undefined
To get a model at a given position, use collection.at .Try
console.log(teamCollection.at(0));
And a demo of those behaviors http://jsfiddle.net/nikoshr/013gjpny/
I'm responsible to make a cache-layer, that uses local storage, that is between the server and the client to lower the bandwidth and server load.
I have two models, 'model' and 'modelContent'. These are connected to each other with an ID.
model is populated as it should be with all the parameters that are in the model.
modelContent is not populated when its content is fully fetched from the server.
I want to wait until the modelContent has it's attribute 'body' fully populated and then add it to the cache. Right now modelContent's 'body'-attribute is just an empty string (which is the default value).
I have created a base-model that model and modelContent inherits from that contains an override for sync for the read-method. The reason for this is that I read http://engineering.linkedin.com/mobile/linkedin-ipad-using-local-storage-snappy-mobile-apps and that is the way I want it to work but with two models that belong together.
I'm very new at BackboneJS and Grails (which the project uses as well) so I'm hoping someone can point me in the right direction.
My base-model:
var basic_model = Backbone.Model.extend({
sync: function(method, model, options) {
if ( method === 'read' ) {
uid = this.get("UID");
if ( uid ) {
var success = options.success;
options.success = function(resp, status, xhr) {
console.log(resp);
}
} else {
Backbone.sync(method, model, options);
}
} else {
Backbone.sync(method, model, options);
}
}
modelContent:
var MailContentItem = basic_model.extend({
urlRoot: project_webroot +'modelContent',
idAttribute: "UID",
defaults: function() {
return _.extend({}, basic_model.prototype.defaults, {
isHTML: false,
body: ""
});
}
});
I am trying to send some JSON data from express to Backbone model.
Update
console.log(response) in parse function of Model prints the values as {"version":"1.0","balance":"80.0"}
console.log(this.model) in the render() function of View gives {}
Server Side Node JS
var express = require('express');
var app = express();
app.listen(3000);
app.get('/getInfo', function(req, res){
//res.setHeader('Content-Type', 'application/json');
res.json({version: "1.0", balance: "80.0"});
});
On Node JS side I have tried following:
app.get('/getInfo', function(req, res){
res.setHeader('Content-Type', 'application/json');
res.send({version: "1.0", balance: "80.0"});
});
Backbone Model
var Bitcoin = Backbone.Model.extend({
url:'http://localhost:3000/getInfo',
parse: function(response) {
console.log(JSON.stringify(response));
return response;
}
});
var info = new Bitcoin ();
info.fetch();
It works fine if I change it to
var info = new Bitcoin ({version: "1.0", balance: "80.0"});
Backbone View
var BitcoinView = Backbone.View.extend({
id:'info',
class:'bitcoin',
template: _.template('<span> <%= balance %> </span>'+
'<span><%= version %></span>'),
render: function() {
console.log(JSON.stringify(this.model));
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
}
});
var bitcoinView = new BitcoinView({model: info});
bitcoinView.render();
$('#app').html(bitcoinView.el);
Console
Uncaught ReferenceError: balance is not defined (from View)
XHR finished loading: "http://localhost:3000/getInfo".
{"version":"1.0","balance":"80.0"} (from parse function)
You are likely trying to render a model that has no values for certain attributes. The template of your view expects these attributes to be present. Add defaults to your model to prevent the template method from causing an error.
var Bitcoin = Backbone.Model.extend({
url:'http://localhost:3000/getInfo',
parse: function(response) {
console.log(JSON.stringify(response));
return response;
},
defaults: {
balance: "",
version:""
}
});
In your view you bind the render to the change event of your model. This way the view will rerender when the model changes (the data is fetched).
this.model.bind("change", this.render, this);
Alternativaly, you need to make sure the data is fetched before rendering the view. You can use the callback function of the fetch function.
info.fetch({
success: function(){
//create view here
}
});
I am trying to load data from an API into a view. However the data doesn't turn up in my view.
I tried getting the collection information in de router, as well as in the model.
However the date won't even console.log the data. Let alone that I can load the data into the view.
I am using require to load the JavaScript files. Can you have a look and see what I am doing wrong here?
I do see this console.log:
console.log("People Collection is initialized");
And I can also see the page loaded and the json. But not the console.log of the data in the url function... In fact I get this error in the console:
Error: A "url" property or function must be specified
In the Backbone Router:
var OF = OF || {};
OF.AdminRouter = Backbone.Router.extend({
routes: {
"users": "goToUsers",
"users/*other": "goToUsers"
},
goToUsers: function() {
require(['./models/users', './views/users_view', './views/menu_view', './collections/user_collection'], function(UsersMdl, UsersView, MenuView, UsersCollection) {
OF.usersView = new OF.UsersView;
OF.usersView.render();
});
}
});
The Collection:
var OF = OF || {};
OF.UsersCollection = Backbone.Collection.extend({
initialize: function() {
console.log("People Collection is initialized");
},
url: function() {
var that = this;
var sendObj = {
"admin": OF.login.attributes.admin,
"session": OF.login.attributes.session
};
$.ajax({
url: 'php/api/users/',
type: "POST",
dataType: "json",
data: sendObj,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("ERR: " + data);
}
});
},
model: OF.UsersMdl
});
The Model:
var OF = OF || {};
OF.UsersMdl = Backbone.Model.extend({
default: {
username: '',
homefoldersize: '',
email: ''
},
initialize: function(){
//on change functions can be done here
OF.usersCollection = new OF.UsersCollection();
OF.usersCollection.fetch();
},
result: {
success: false,
message: ''
},
validate: function(att) {
}
});
The View:
var OF = OF || {};
OF.UsersView = Backbone.View.extend({
el: '#content',
remove: function() {
this.$el.empty();
this.stopListening();
return this;
},
initialize: function() {
//set the new address variable.
OF.usersMdl = OF.usersMdl || new OF.UsersMdl();
},
render: function() {
/*
//first check if you are allowed to see this page
if (!OF.login || !OF.login.isValid()) {
OF.router.navigate('login', {trigger: true});
return;
}
*/
//save this in that
var that = this;
//when importing of login page (and fill it with info) is done
$.when(OF.template.get('users-usersField', function(data) {
var htmlSource = $(data).html();
var template = Handlebars.compile(htmlSource);
var compiled = template(OF.usersMdl.attributes);
//now place the page
that.$el.html(compiled);
//then start the menu
})).then(function(){
setTimeout(function(){
OF.menuView = new OF.MenuView;
OF.menuView.render();
}, 100);
});
$('#logout').show();
}
});
Thanks.
It seems to call the initialize of the collection twice and then continues to call the json function.
In your model's initialization you have
OF.usersCollection = new OF.UsersCollection();
OF.usersCollection.fetch();
But when you fetch your collection, it's going to initialize models for every result it gets back ... which will then trigger fresh collection fetches.
You don't need to create collections for your models inside your models, especially if the model is being created by the collection. Whenever you add a model to a collection (including when the collection creates the model after a fetch) the collection will associate itself with the model.
The general order of things should be:
You define a url function on your collection which returns the URL where you can get the (raw JSON) models of that collection.
You instantiate that collection, and then call fetch on the instance
The collection makes an AJAX call (which you can affect by overriding fetch or sync) and gets back the raw JSON for all of the models.
The collection instantiates new models for each result it gets back; those models are automatically added to the collection, and their .collection is automatically set to the collection.
Once OF.usersCollection.fetch().done(function() {... you can have your views start doing things, as your collection should now be all set.
I have a rails controller which sends a mash-up of models as a global json object. Something like this
{
dogs : { species: {}, ...},
cats : { food: {}, ...},
foxes : { },
...,
...
}
On my client side, I have all these entities neatly segregated out into different backbone models and backbone collections.
On some onchange event, I need to send a mashup of some model attributes back to the server as a HTTP POST request and the server sends a response which again spans values across a few models.
How do I setup Backbone.sync to deal with such an ajax scenario? I do not want to change the rails backend because its quite a steady implementation. Or do I make vanilla $.ajax requests through jQuery in one of my backbone views and handle it in a callback on ajax success/failure?
I think there are a couple of ways to do this via backbone. I think I'd start out with a model to represent the mashup:
var MashupModel = Backbone.Model.extend({
});
Then you can pass in any models like you would normally (or a collection for that matter):
var my_mash = new MashupModel({
dog: dogModel.toJSON(),
cat: catModel.toJSON(),
foxes: foxCollection.toJSON()
});
// do stuff if you need...
Then do what you want when the response comes back like normal:
my_mash.save({}, {
success: function(model, response) {
// do stuff here to put new data into the proper models / collections
},
error: function() { alert("I FAIL!"); }
});
That's all well and good... however, I think it would be better to push the above down into the MashupModel object instead of at the request level. Again, several ways:
var MashupModel = Backbone.Model.extend({
initialize: function(attrs) {
// can't remember the actual code, but something along the lines of:
_.each( attrs.keys, function(key) {
this.set(key, attrs.key.toJSON();
});
},
save: function(attrs, opts) {
var callback = opts.success;
opts.success = function(model, response) {
// do your conversion from json data to models / collections
callback(model, response);
};
// now call 'super'
// (ala: http://documentcloud.github.com/backbone/#Model-extend)
Backbone.Model.prototype.set.call(this, attrs, opts);
}
});
Or you could override toJSON (since backbone calls that to get the attrs ready for ajax):
// class definition like above, no initilize...
...
toJSON: function() {
// again, this is pseudocode-y
var attrs = {};
_.each( this.attributes.keys, function() {
attrs.key = this.attributes.key.toJSON();
});
return attrs;
}
...
// save: would be the same as above, cept you'd be updating the models
// directly through this.get('dogs').whatever...
Now, you can just do:
var my_mash = new MashupModel({
dog: dogModel,
cat: catModel,
foxes: foxCollection
});
// do some stuff...
my_mash.save({}, {
success: function(model, response) {
// now only do stuff specific to this save action, like update some views...
},
error: function() { alert("I FAIL!"); }
it would be possible, but may be difficult to modify backbone.sync to work with this structure. i'd recommend going with plain old jquery $.ajax requests. then on success, pull the info apart and populate your collections.
$.get("/whatever", function(data){
catCollection.reset(data.cats);
dogCollection.reset(data.dogs);
// etc
});
data = {};
data.cats = catCollection.toJSON();
data.dogs = dogCollection.toJSON();
// etc
$.post("/whatever", data);