Pretty new to Backbone, so please mind my ignorance...
I have a simple GallereyModel:
var GalleryModel = Backbone.Model.extend({
defaults : {
id: "",
width: ""
},
url : ""
});
When the model is updated, the function galleryModelUpdate is called
var GalleryView = Backbone.View.extend({
initialize: function () {
this.listenTo(this.model, "change", this.galleryModelUpdate);
},
galleryModelUpdate: function(){
console.log("updated gallery model"+this.model.get("id");
if (this.model.get("url")){
console.log("fetching " + this.model.get("url")); // this line prints with the correct url
this.model.fetch({ // this line gives error
success: function(){
console.log("fetched succesfully!");
}
});
}
}
});
I am printing the value of url on the model before fetch is called, so not sure why is it throwing the "url" undefined error?
Many thanks for your help in advance
Either the url or the urlRoot model properties needs to be defined in order for the model to fetch.
You can set your model url to point to the url data attribute:
Backbone.Model.extend({
url: function () {
return this.get('url');
}
});
Related
I hate to ask these strange problems but couldn't able to avoid this one.
I have "Option" view with "Option" model passed as a parameter when creating.
var optionView = new OptionView({ model: option });
this.$el.find('div#optionsBoard').append( optionView.render().el );
In this view, when the user clicks on "Vote" button, the "voteCount" attribute of the model will be incremented.
events: { 'click .button-vote': 'processVote' },
processVote: function (e) {
var voteCounted = this.model.get('voteCount');
this.model.set('voteCount', voteCounted++);
console.log(this.model.id); // has a Id value
console.log(this.model.isNew()); // false
this.model.save(); // occurs problem here
e.preventDefault();
},
The problem occurs when I save the model back to the server as following:
PUT http://localhost:13791/api/options/ 404 (Not Found)
Yes, this url actually isn't existed on my REST API server. But I believe the correct path of PUT URL to update the model should be as following:
PUT http://localhost:13791/api/options/id_of_the_entity_to_be_updated
When I test this PUT url (http://localhost:13791/api/options/id_of_the_entity_to_be_updated) with Postman Rest client, it works perfectly.
So I think the problem occurs because Backbone model.save() method does not add the id_of_the_entity_to_be_updated to the PUT url.
Please, suggest me something how should I solve this problem.
As additional description, this is my "option" model setup code.
define([
'backbone'
], function (Backbone) {
var Option = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
name: '',
location: '',
link: '',
voteCount: 0,
expiredDate: Date.now(),
imageName: ''
},
url: '/api/options/',
readFile: function(file) {
var reader = new FileReader();
// closure to capture the file information.
reader.onload = ( function(theFile, that) {
return function(e) {
that.set({filename: theFile.name, data: e.target.result});
that.set({imageUrl: theFile.name});
console.log(e.target.result);
};
})(file, this);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
});
return Option;
});
Problem found
My bad. In the "Option" model setup, it should be "urlRoot" instead of "url".
In your model you should use urlRoot instead url:
urlRoot: '/api/options/'
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
I have a backboneJS app that has a router that looks
var StoreRouter = Backbone.Router.extend({
routes: {
'stores/add/' : 'add',
'stores/edit/:id': 'edit'
},
add: function(){
var addStoresView = new AddStoresView({
el: ".wrapper"
});
},
edit: function(id){
var editStoresView = new EditStoresView({
el: ".wrapper",
model: new Store({ id: id })
});
}
});
var storeRouter = new StoreRouter();
Backbone.history.start({ pushState: true, hashChange: false });
and a model that looks like:
var Store = Backbone.Model.extend({
urlRoot: "/stores/"
});
and then my view looks like:
var EditStoresView = Backbone.View.extend({
...
render: function() {
this.model.fetch({
success : function(model, response, options) {
this.$el.append ( JST['tmpl/' + "edit"] (model.toJSON()) );
}
});
}
I thought that urlRoot when fetched would call /stores/ID_HERE, but right now it doesn't call that, it just calls /stores/, but I'm not sure why and how to fix this?
In devTools, here is the url it's going for:
GET http://localhost/stores/
This might not be the answer since it depends on your real production code.
Normally the code you entered is supposed to work, and I even saw a comment saying that it works in a jsfiddle. A couple of reasons might affect the outcome:
In your code you changed the Backbone.Model.url() function. By default the url function is
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
This is the function to be used by Backbone to generate the URL for model.fetch();.
You added a custom idAttribute when you declared your Store Model to be like the one in your DB. For example your database has a different id than id itself, but in your code you still use new Model({ id: id }); when you really should use new Model({ customId: id });. What happens behind the scenes is that you see in the url() function it checks if the model isNew(). This function actually checks if the id is set, but if it is custom it checks for that:
isNew: function() {
return !this.has(this.idAttribute);
},
You messed up with Backbone.sync ... lots of things can be done with this I will not even start unless I want to make a paper on it. Maybe you followed a tutorial without knowing that it might affect some other code.
You called model.fetch() "a la" $.ajax style:
model.fetch({
data: objectHere,
url: yourUrlHere,
success: function () {},
error: function () {}
});
This overrides the awesomeness of the Backbone automation. (I think sync takes over from here, don't quote me on that).
Reference: Backbone annotated sourcecode
I'm using a Router to organise my Backbone app. In my edit route I'm calling fetch on a model instance to get the model's data for the edit form:
App.Router = Backbone.Router.extend({
routes: {
"": "index",
"edit(/:id)": "edit"
},
index: function () {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
},
edit: function (id) {
this.formEditItem = new App.Views.FormEditItem({model: this.getItemByID(id), parent: this});
},
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: this.onModelFetchError
})
},
onModelFetchError: function (model, response, options) {
this.showError(response.responseText);
},
showError: function(msg) {
this.error = new App.Views.Error({parent: this, message: msg});
}
});
The fetch call works fine, but I'm having trouble handling errors. I want to instantiate an Error view and display the message in it. But when I try this code, I get "Uncaught TypeError: Object [object global] has no method 'showError'". It seems that assigning onModelFetchError as the handler for fetch errors puts it in the global scope, even when I bind it to the Router with _.bindAll.
Is there any simple way to ensure onModelFetchError remains in the Router scope?
You are calling to _.bindAll() inside of the index function which is fired by the route "", so if you don't fire that route they'll never get bind to the context object. I would suggest to create an initialize method for your router so you can bind all the functions for any route inside of it.
initialize: function() {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
}
Try with
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
var self = this; // this changed
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: self.onModelFetchError // this changed
})
},
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.