backbone.js set callback on before save? - backbone.js

I was asked to remove couple of attributes from a backbone model (which was optional) where they exists. My first intent was to place something like a before_save callback on a model. But i didn't find any information googling.
is it possible to do that on a backbone side?

Just override default Model.save and add your callback to it.
var MyModel = Backbone.Model.extend({
save: function (key, val, options) {
this.beforeSave(key, val, options);
return Backbone.Model.prototype.save.call(this, key, val, options);
},
beforeSave: function (key, val, options) {
}
})
If you want only to remove particular attributes from being sent to the server than you may override Model.toJSON method.

Related

Can I save changed attributes of model after several set

I call set method multiple times and change several attributes. Then I want to send the changed data to the server with {patch: true}.
I can use model.save(attrs, {patch: true});, but I do not know attrs. I can't use model.toJSON() (unneeded fields) or model.changedAttributes() (only last set) to obtain attrs.
How can I do this?
According to changedAttributes:
Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model.
So you could try caching the state of model using toJSON before you start modifying. Once your modifications are done, pass the new state to changedAttributes method to retrieve changed attributes hash and then send a patch request. Something like
var oldAttrs = model.toJSON();
// ...do modifications here
var changedAttrs = model.changedAttributes(oldAttrs);
dataTosend = model.pick(_.keys(changedAttrs));
model.save(dataTosend, {patch: true});
Bind a listener for model
If you are setting value in view, listener should be like (better write it in initialize function)
this.listenTo(this.model, "change", this.onModelValueChange);
And your listener function
onModelValueChange: function(model, args) {
model.save(args.changed, {patch: true});
}
While TJ has the right answer, I have a better way to achieve what he suggest.
Instead of making a raw clone of the attributes, I prefer to keep a master copy of the model at the start of the app or the initialize of the view.
this.master = this.model.clone();
// ... then changes are made to this.model
When ready to save, use the master model to compare the attributes and retrieve the changes directly.
var changes = this.master.changedAttributes(this.model.attributes);
if (changes !== false) this.model.save(changes, { patch: true });
With this, you can skip the dataTosend = model.pick(_.keys(changedAttrs)) altogether since changes already is an object of all the differences with the initial state of the master model.
If it's a view that is re-used after the model save:
var View = Backbone.View.extend({
initialize: function() {
this.updateMaster();
},
saveChanges: function() {
var changes = this.master.changedAttributes(this.model.attributes);
if (changes !== false) {
this.model.save(changes, {
patch: true,
context: true,
success: this.updateMaster
});
}
},
updateMaster: function() {
this.master = this.model.clone();
},
});

Backbone.js / require.js - Override model function to work with backend as a service

Good morning guys. I have a little understanding problem with backbone.js. i have a javascript sdk from a backend as a service with some getter and setter methods to get datas from this platform.
I have load this javascript sdk with require.js an it´s work fine. Now i need to create some models that work with this getter and setter methods to get this data to my collection an finally to my view. I do not have any clue...maybe someone have the right idea for me.
This is my current model:
define(['jquery','underscore','backbone'], function($,_,Backbone) {
var holidayPerson = Backbone.Model.extend({
initialize: function() {
console.log("init model holidayPerson");
this.on("change", function(data) {
console.log("change model holidayPerson"+JSON.stringify(data));
});
}
});
return holidayPerson;
});
Actually i create an instance of my model in my view:
define(['jquery','underscore','backbone','text!tpl/dashboard.html','holidayPerson','apio'], function($,_,Backbone,tpl, holidayperson, apio) {
template = _.template(tpl);
var usermodel = new holidayperson();
var dashboardView = Backbone.View.extend({
id: 'givenname',
initialize: function() {
console.log("dashboard view load");
usermodel.on('change', this.render);
var user = new apio.User();
user.setUserName('xxx');
user.setPassword('xxx');
apio.Datastore.configureWithCredentials(user);
apio.employee.getemployees("firstName like \"jon\" and lastName like \"doe\"", {
onOk: function (objects) {
console.log("apio: " + JSON.stringify(objects));
usermodel.set({mail: objects[0]['data']['mail'],lastname: objects[0]['data']['lastName'], username: objects[0]['data']['userName'], superior: objects[0]['data']['superior']});
}
});
},
render: function() {
console.log("render dashboard view");
console.log(usermodel.get('mail'));
console.log(usermodel.get('lastname'));
this.$el.html(template());
return this;
}
});
return dashboardView;
});
I think this not the right way...can i override the getter and setter method from this model ? Or maybe the url function ? Anyone now what is the best practice ?
Thanks a lot :-)
First of all, make sure that your render operation is asynchronous, as your API call will be and the usermodel params won't be set until that operation completes. If you render method fires before that, it will render the empty usermodel, since the data will not be there yet.
Second, a model need not fetch its own data, in my opinion. If you are going to have multiple users, you could use a collection to hold those users and then override the collection's sync method to handle the fetching of data from the API, but if there's no collection, it seems logical to me to have a method that does the data fetching and setting thereafter, as you've done.

Backbone - user case

Say a user is going down a page and checking off and selecting items.
I have a Backbone model object, and each time the user selects something I want to update the object.
I have this in a separate JavaScript file that I source in my HTML:
var app = {};
var newLineup = null;
var team = document.getElementsByName('team');
app.Lineup = Backbone.Model.extend({
defaults: {
team: team,
completed: false
},
idAttribute: "ID",
initialize: function () {
console.log('Book has been intialized');
this.on("invalid", function (model, error) {
console.log("Houston, we have a problem: " + error)
});
},
constructor: function (attributes, options) {
console.log('document',document);
console.log('Book\'s constructor had been called');
Backbone.Model.apply(this, arguments);
},
validate: function (attr) {
if (attr.ID <= 0) {
return "Invalid value for ID supplied."
}
},
urlRoot: 'http://localhost:3000/api/lineups'
});
function createNewLineupInDatabase(){
newLineup = new app.Lineup({team: team, completed: false});
newLineup.save({}, {
success: function (model, respose, options) {
},
error: function (model, xhr, options) {
}
});
}
When the user first accesses the page, I will create a new lineup object by calling the above function. But how do I update that object as the user interacts with the page? Is there a better way to do this other than putting the Backbone model object at the top of my JavaScript file?
The Backbone pattern was designed to answer your question. As other respondents said, wire up a View, which takes your model as a parameter and lets you bind DOM events to the model.
That said, you don't have to use the rest of the framework. I guess you can use all the functionality Backbone provides models by handling the model yourself.
You need to worry about a couple of things.
Give you model a little encapsulation.
Set up a listener (or listeners) for your checkbox items.
Scope the model to your app
Backbone provides neat encapsulation for your model inside a View, but if you can live with it, just use your app variable which is within scope of the JavaScript file you posted.
When you're ready to instantiate your model, make it a property of app:
app.newLineup = new app.Lineup({team: team, completed: false});
It may look weird to have the instance and the constructor in the same object, but there aren't other options until you pull out the rest of Backbone.
The listener
So you have N number of checkboxes you care about. Say you give them a class, say, .options. Your listener will look like
$( ".options" ).change(function() {
if(this.checked) {
//Do stuff with your model
//You can access it from app.newLineup
} else {
}
});
Voila! Now your page is ready to talk to your model.
If there is frontend ui / any user interaction within your code it is extremely useful to create a backbone view which makes use of an events object where you can set up your event handler.
You can also link a view to a model to allow your model / your object to be updated without scope issues.

Is there an equivalent to parse to use before syncing with the server?

In my backbone model, I parse the response from the server:
var MyModel = Backbone.Model.extend({
urlRoot: "/users",
parse: function(response){
var data = {};
data.id = reponse.userDetails.id;
data.name = response.userDetails.firstname + " " + response.userDetails.lastname;
data.description = response.userDetails.description;
return data;
}
});
var myModel = new MyModel({id: 1});
myModel.fetch();
The views that use this model can manipulate it, for example, if the user were to click on the view to "select" it, it would update the model...
myModel.set({selected: true});
...and the view would re-render based on the model's change event and highlight the "selected" user.
When it comes time to save the model to the server, how do I only send the attributes the server wants? and ignore the attributes which were added through user interaction.
OR
Should the data model always reflect what the server returns? If so, is there a better way to store the user interactions (whether the view is "selected")? Should it be a separate model than the actual data model?
Thanks
The model doesn't need to mirror the data on the server if that doesn't make sense for your application.
For the model's attributes, if you don't need to render those attributes in a template, then you can just override model.toJSON() to only serialize the attributes you want sent to the server. Be careful though, in this case if you are rendering your template (or anything else) using this.model.toJSON() then it will also be affected. If that's a problem then you can override model.sync() instead and manipulate the data passed in before sending it to Backbone.sync. For example:
var myModel = Backbone.Model.extend({
sync: function (method, model, options) {
// remove the unwanted attributes. Something like...
options.attrs = _.pick(model.attributes, 'attribute1', 'attribute2', 'attribute3');
return Backbone.sync.call(this, method, model, options);
}
});
Overriding model.toJSON as suggested by mu_is_too_short worked nicely for me.
In the model
function() {
var json = Backbone.Model.prototype.toJSON.call(this);
json.ExtendedFieldData = JSON.stringify(json.ExtendedFieldData);
return json;
},
We use model.attributes for templates.

How can I populate the backbone model if I overrode 'fetch'?

I'm building some JS to access Google places JS API using backbone. So far I'm really stuck with the model bindings.
I overrode 'fetch' to be able to use the Google API. The call to Google works just fine.
var Places = Backbone.Collection.extend({
model: Place,
fetch: function(options) {
// SNIPPET //
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, this.googlePlaceCallback);
// SNIPPET //
},
parse: function(response){
// nerver called
},
googlePlaceCallback: function(results, status) {
// I do something here and is properly called after Google returns a response
}
});
I also defined a very simple View:
var MapView = Backbone.View.extend({
initialize: function() {
this.model = new Places();
this.model.bind("reset", this.render, this);
this.model.fetch();
},
render : function () {
console.log( this.model.toJSON() );
}
});
I can't figure out how to populate the 'model'. Google returns the expected results, but I can set them to the backbone model. I there something I need to do in 'googlePlaceCallback'? I'll probably will need to override 'parse' also since Google results are not quite all interesting.
Assuming that results is a collection of the results you want, you should be able to implement the callback as follows:
googlePlaceCallback: function(results, status) {
this.add(results);
}
Since Places is a backbone Collection, you're just calling the following method in the above code: http://backbonejs.org/#Collection-add
You will also have to get the correct this reference inside the googlePlaceCallback function (you want this to be the Collection). One way to do that is to use Underscores bindAll method ( http://underscorejs.org/#bindAll ), which you can use to make sure all methods in the Backbone class have a this context of the Collection itself. You can do this on initialize as follows:
initialize: function() {
_.bindAll(this);
}
Also, the reason parse is not being called is because you are overriding fetch, and fetch calls parse. If you take a look at the annotated backbone code, you will be able to see the method call: http://backbonejs.org/docs/backbone.html

Resources