backbone:CRUD - (create)Post Data - save is not a function - javascript

i have created a backbone model like mentioned below
LoginModel = Backbone.View.extend({
initialize: function(){
},
defaults:{
username: 'XXXXX#XXXXX.com',
password: 'XXXXXXXXX'
},
urlRoot: 'https://XXXXX.portnumber/xxxxxx/xxxxxx/',
url: 'xxxxxxxxxx'
});
I am creating a login model instance and calling the method Save
var loginmodel = new LoginModel();
loginmodel.save({username:'xxxxxxx',password:'xxxxxxxx'},{
success: function(model, response){
console.log('success saved'+response);
},
error: function(model, response){
consoloe.log('failed saved'+response);
}});
Here i am getting an error
[06:22:39.742] TypeError: loginmodel.save is not a function
its not calling the backbone's save method to post the data to the server.

eh... I think you extend the wrong class, it should be a model, right?
LoginModel = Backbone.View.extend({
this line create a view, not a model. Backbone's View don't have save() method, so you got that error. You need:
LoginModel = Backbone.Model.extend({
and try other staff again.

Related

TypeError: this.model.toJSON is not a function

I am getting the above title error in firebug. Not sure what can be the problem..
My View
app.View.TrendsView = Backbone.View.extend({
template: _.template($('#trends-template').html()),
render: function() {
this.$el.empty();
this.$el.html(this.template({
trends: this.model.toJSON()
}));
return this.$el;
}
});
calling
app.views.trends = new app.View.TrendsView({ model : model });
Firebug
My model creation
var m = new app.Model.TrendModel();
m.url='/trends'
m.set('login', login);
m.save(null, {
success: function(collection, model, response){
app.views.trends = new app.View.TrendsView({
model : model
});
$('#tab-content').empty();
$('#tab-content').append(app.views.trends.render());
},
error: function(collection, model, response){
}
});
m.destroy();
Spring code
#RequestMapping(value = "/trends", method = RequestMethod.POST, produces = "application/json")
#ResponseBody
public TrendResultDTO getTrends(#RequestBody UserDTO user,
HttpServletResponse response) {
From the documentation on model.save
save accepts success and error callbacks in the options hash, which
will be passed the arguments (model, response, options)
but the arguments your callbacks expect are collection, model, response which means you pass your response as model to your view, as demonstrated by your console log.
Try
m.save(null, {
success: function(model, response, options){
app.views.trends = new app.View.TrendsView({
model : model
});
// ...
},
error: function(model, response, options){
}
});

cakephp backbone save not working

I have a site developed in cakephp where I'm using a simple app in backbone.
Now I would like to save data from backbone but doesn't work, return always inside callback error, and it doens't take the right value to save inside table.
This is my simple app:
TaskModel = Backbone.Model.extend({
url: function(){
return "/step_task/ajax_save";
}
});
TaskCollection = Backbone.Collection.extend({
model: TaskModel,
initData: function(data){
return data;
}
});
var TaskView = Backbone.View.extend({
template: _.template($("#task-template").html()),
initialize: function(){
this.task = new TaskCollection(<?php echo json_encode($step['StepTask']); ?>);
this.render();
},
render: function(){
taskModel = new TaskModel({
'id': '1',
'user_id': '1'
});
//--------------------------- here I would like to save inside my table ----------------
taskModel.save(null, {
success: function(model, response) {
console.log('success');
console.log(model);
console.log(response);
},
error: function(model, response) {
console.log('error');
console.log(model);
console.log(response);
},
wait: true // Add this
});
$(this.el).html(this.template({tasks: this.task.models}));
}
});
and this is my funciton inside StepTaskController.php
public function ajax_save(){
$this->autoRender = false;
$this->StepTask->save($this->request->data);
}
How can I solve it?
Try to change the url in your model to urlRoot :
TaskModel = Backbone.Model.extend({
urlRoot: '/step_task/ajax_save'
});

Update StackMob User Object JS-SDK

I am trying to update a user object using the JS-SDK but I am getting Duplicate key for schema error. What is the correct way to update a user object using StackMob JS-SDK? Below is my code
var Usr = StackMob.Model.extend({schemaName: 'user'});
var rid = window.localStorage.getItem("devicetoken");
var usr = new Usr({ username: rid });
usr.set({sendnotification: true });
usr.save({
success: function(model, result, options) { console.log('saved'); },
error: function(model, result, options) {console.debug('failed:'+result.error);}
});
Figured out the answer, you need to use the User object directly. There is no need to extend the model
var user = new StackMob.User({ username: rid, sendnotification: true});
user.save({
success: function(model, result, options) { console.log('saved'); },
error: function(model, result, options) {console.debug('failed:'+result.error);}
});

class methods in Backbone

I'm trying to implement authentication with Devise (an authentication gem for Rails) using Backbone. Users can sign out of Backbone by sending the DELETE request to /users/sign_out/ so I couldn't get this link to work because if I click it it's a GET request
<li>sign out</li>
I then created a logout method on the User model, but to trigger it I have to have an instance of the user model (obviously). I created a logout method in the router that gets triggered by navigating to the logout route, but since I can only call logout on the user model with an instance of it, I'm creating a new model in the logout method just to call logout.
"logout": "logout"
},
logout: function(){
var foo = new app.Models.User
foo.logout();
}
This is obviously a bad idea but I don't know what else to do. Can you recommend what I should be doing instead? Is there a way to make the logout a class method so I don't have to instantiate a new model just to logout or something else?
Update
This is the createUser method in the User model that sends the registration data to devise. In the success callback, it assigns the session to a variable window.app.current_user = userSession;. I also have a logout method on the user model that I try to call from the router like this
logout in router
logout: function(){
window.app.current_user.logout();
}
--
app.Models.User = Backbone.Model.extend({
initialize:function () {
},
createUser: function() {
var user = {};
user['email'] = this.get("email");
user['password'] = this.get("password");
user['password_confirmation'] = this.get("password_confirmation");
var registration = {};
registration['user'] = user;
var _this = this;
$.ajax({
url: '/users.json',
type: "POST",
data: {user: user, registration: registration},
success: function(userSession, response) {
window.app.current_user = userSession;
},
... code ommitted
logout: function(){
var me;
console.log("Logging out...");
me = this;
return $.ajax({
url: '/users/sign_out',
type: "DELETE",
dataType: "json",
success: function(data, textStatus, jqXHR) {
window.app.current_user = '';
},
error: function(jqXHR, textStatus, errorThrown) {
return alert("Error logging out: " + errorThrown);
}
});
},
I am slightly confused why you would want to trigger a logout function when the User model has not already been created. Could you please explain your reasoning behind having this logout function in your router?
Personally, I would have a Session model which listens to the click event of your link. This will then call a logout method which will make the DELETE request.
UPDATE
Here is a quick JsFiddle which shows creating a model and attaching it to a global variable:
http://jsfiddle.net/Francium123/eBG3E/2/
var User = Backbone.Model.extend({
initialize:function () {
this.name = "MyName";
this.password = "password"
},
login:function(){
console.log("login called");
},
logout: function(){
console.log("logout called");
}
});
window.MyModels = window.MyModels || {};
window.MyModels.User = new User();
console.log(window.MyModels.User.login());
console.log(window.MyModels.User.logout());
Please note that this is just an example, I doubt you would want to store the password in the model!
Additionally you should be able to use Backbone Models fetch(GET), save(POST/PUT), destroy(DELETE) methods instead of writing ajax requests directly in the model. If needs be you can override the models sync method.

Adding options to backbone.js model.save()

Is it possible to pass inside the options of the "save" method - a diffrent url/path for the request ?
The default urlRot for the model is --> urlRoot: "/users"
is it possible to do something like that:
this.model.save({
'userName': $('#userName').val(),
'password': $('#password').val()},{
url: "/users/login",
success: function(model, response, options) {
},
So the request, this time, will be sent to "/users/login" and NOT to "/users" ?
From the documentation:
urlmodel.url()
Returns the relative URL where the model's resource
would be located on the server. If your models are located somewhere
else, override this method with the correct logic. Generates URLs of
the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if
the model is not part of a collection.
So it looks as if you can provide your own url function on a model.
Example:
var MyModel = Backbone.Model.extend({
use_custom_url: false,
url: function() {
if (use_custom_url) {
return "/users/login";
} else {
return Backbone.Model.prototype.url.apply(this);
}
}
});

Categories