Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending extra, non-model data in a save request with backbone.js?

I'm looking for a solution for dealing with an issue of state between models using backbone.js.

I have a time tracking app where a user can start/stops jobs and it will record the time the job was worked on. I have a job model which holds the job's data and whether it is currently 'on'.

Only 1 job can be worked on at a time. So if a user starts a job the currently running job must be stopped. I'm wondering what the best solution to do this is. I mean I could simply toggle each job's 'on' parameter accordingly and then call save on each but that results in 2 requests to the server each with a complete representation of each job.

Ideally it would be great if I could piggyback additional data in the save request similarly to how it's possible to send extra data in a fetch request. I only need to send the id of the currently running job and since this really is unrelated to the model it needs to be sent alongside the model, not part of it.

Is there a good way to do this? I guess I could find a way to maintain a reference to the current job server side if need be :\

like image 544
Will Avatar asked Mar 20 '12 12:03

Will


1 Answers

when you call a save function, the first parameter is an object of the data that's going to be saved. Instead of just calling model.save(), create an object that has the model data and your extra stuff.

inside of your method that fires off the save:

...
var data = this.model.toJSON();
data.extras = { myParam : someData };

this.model.save(data, {success: function( model, response ) {
    console.log('hooray it saved: ', model, response);
});
...
like image 98
ryanmarc Avatar answered Nov 04 '22 11:11

ryanmarc