Backbone documentation says,
parse is called whenever a model's data is returned by the server, in
fetch, and save. The function is passed the raw response object, and
should return the attributes hash to be set on the model.
But i have customized parse function for my model. I want to execute it only when i fetch data not when i save data.
Is there a way to do it? I can check my response inside parse function. But is there any built-in option to do it?
This is from the backbone source file regarding saving a model:
var model = this;
var success = options.success;
options.success = function(resp) {
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
You could pass a custom option on your save like: model.save(null, { saved: true }), then in your custom parse:
parse: function(response, options) {
if ( options.saved ) return this.attributes;
// do what you're already doing
}
I haven't tested this at all, but it should at least get you started.
Just pass a parse:false into the save method as an option.
m = new MyModel()
s.save(null, {parse: false})
Related
I have a model which keeps some other models in an attribute array. When these models are stored, however, I don't want to keep the sub-modules around--instead, I want to store the primary keys, and then when the model is fetched from the server, its parse will "reconstitute" them by fetching the related models.
What is the best approach to accomplishing this? The closest I've come to getting it to work is overriding the sync method:
sync : function(method, model, options) {
var topics = this.get('topics');
model.attributes.topics = _.pluck(topics, 'id');
var ret = Backbone.Model.prototype.sync.call(this, method, model, options);
this.attributes.topics = topics;
return ret;
},
but this regularly fails, leaving the keys in the attributes instead of the full models & consequently crashing.
Parse function (slightly paraphrased):
parse : function(response) {
response.topics = _.map(response.topics, function(item) {
return app.topics.getByPK(item);
}
return response;
}
What I would do would be something more along these lines:
parse : function(response) {
this.topics = _.map(response.topics, function(item) {
return app.topics.getByPK(item);
}
return response;
}
Which keeps your array of ids intact at all times, and you have access by using this.topics instead of this.get('topics') or this.attributes.topics
Disk is my collections object. I need to stop fetching collections
customPoll: function(time){
var set_time = 0;
if(time === undefined){
set_time = 4000;
}
var route = Backbone.history.fragment.split('/');
var self = this;
if(route[0] === "disks"){
setTimeout(function() {
Disks.fetch({update:true,success: function(){
self.customPoll();
}, error: function(){
self.customPoll();
}
});
}, set_time); //TODO Need to handle efficiently...
}
}
Am trying to call this fetching in every 4 second if some condition exist other wise i need to stop calling this fetching.
var route = Backbone.history.fragment.split('/');
var smart = new Smart.model({
"id" : route[1]
});
var self = this;
smart.save(null,{
success: function(model,event,response){
model = Disks.get(route[1]).toJSON();
$('#smart-confirm-dialog').modal('hide');
self.showStatusMsg(1,"<b> S.M.A.R.T. Test : </b>S.M.A.R.T Test started succesfully");
if(model.smart.progress === "100%"){
self.clearAllTimeout();
alert("please stop fetching....pleaseeee");
// Stop polling here . then fetch information from smart.fetch api.
Smart.fetch({update: true}); //this is another api i need to call this api now.
}else{
self.customPoll();
}
});
But it seems to be not working... Its keep on fetching collection.. How can i stop this Disk collection fetching.
My answer maybe is funny, I want to add comment, but I couldn't. can you add new field to your model and
customPoll: function(time){
var disks = this.model.toJSON();
if(disks.yourField){
// here your code
}
}
but before saving the model need to do delete disks.yourField;
I gave up finally. I have struggling to get this one to work but no luck. I simply have a collection.create call like this:
var createData = {
full_name : full_name,
email : email,
role_id : role_id
};
var that = this;
app.collections.teamMembers.create(createData,{
wait: true,
success : function(){
log("in success")
},
error : function(a,b,c){
log("in error")
}
})
The server is PHP and it returns the result like this:
header('Content-type: application/json');
echo json_encode(array(
"data" => $data,
"meta" => $meta
));
In the above, the $data is actually the array("attr"=>"val", ...) which matches exactly how the model for this collection is defined.
The problem is that since I am not returning directly a JSON object similar to the original model, but using namespacing (data/meta), I use model.parse on the model like this:
parse : function(response){
log(response, "inside model parse, this is the response from server")
return response.data;
},
ISSUE: The model doesn't get created on the client end. No 'add' event is fired. I am also using the wait:true option.
However, the model gets created on the local if:
- I don't use wait:true
- I use wait true but return the exact JSON model from server, with no name spacing.
I WANT to use wait:true as well as namespacing. Please help :(
Finally I was able to fix it, I was overriding backbone collections and models in my bootstrap to have a loading state which I am not using anyway. So I commented out that whole code. Now it works fine. this was the code in my bootstrap that I commented out:
// OVERRIDINGS AND SETTINGS
//----------------------
// Adding close method to all views
Backbone.View.prototype.close = function() {
if (this.onClose) {
this.onClose();
}
_.each(this.childViews, function(childView){
childView.close();
delete childView;
})
this.remove();
this.unbind();
};
// Adding loading state to every model and collection
Backbone.Collection.prototype.loading = false;
Backbone.Model.prototype.isLoading = false;
// Set isLoading to true when fetch starts
var oldFetch = Backbone.Collection.prototype.fetch;
Backbone.Collection.prototype.fetch = function(options) {
this.isLoading = true;
oldFetch.call(this, options);
}
Backbone.Model.prototype.fetch = function(options) {
this.isLoading = true;
oldFetch.call(this, options);
}
// Turn off isLoading when reset
Backbone.Collection.prototype.on('reset', function(){
this.isLoading = false;
})
Backbone.Model.prototype.on('reset', function(){
this.isLoading = false;
})
Can someone explain how JSON.stringify() magically ONLY stringifies JSON as fetched by URL and does NOT bother with other backbone-specific parts of the full collection object?
I am curious about underlying implementation and/or design patterns that explain this very impressive capability. I had to use json2.js to get stringify functionality, so I don't think backbone is overriding or decorating stringify.
I discovered that if I pass a collection directly to JS OBJECT code, the code "sees" model keys and other backbone-specific parts of a collection object, whereas if I perform JSON.stringify THEN jquery.parseJSON on that stringified object, my code "sees" only the JSON as returned by URL.
Code:
enter code here
$(function () {
var Person = Backbone.Model.extend({
initialize: function () {
// alert("Model Init");
}
}),
PersonList = Backbone.Collection.extend({
model: Person,
url: '/Tfount_Email/Email/SOAInbox',
initialize: function () {
// alert("Collections Init");
}
}),
personlist = new PersonList();
personlist.fetch({
error: function () {
alert("Error fetching data");
},
success: function () {
// alert("no error");
}
}).complete(function () {
// first call to makeTable w collection obj, we see MORE than just the JSON returned by URL
makeTable(personlist);
// stringify then parse, we see only JSON returned by URL
jsonString = JSON.stringify(personlist);
var plistJSON = jQuery.parseJSON(jsonString);
makeTable(plistJSON);
});
});
function makeTable(obj) {
var type = typeof obj
if (type == "object") {
for (var key in obj) {
alert("key: " + key)
makeTable(obj[key])
}
} else {
alert(obj)
}
}
This is the intended and by-design behavior of JSON.Stringify. From Douglas Crockford's JSON2.js file:
When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified.
https://github.com/douglascrockford/JSON-js/blob/master/json2.js#L38-39
When you call JSON.stringify on a Backbone.Collection, it calls that collection's toJSON method, as described by this comment.
Using the Backbone.Rpc plugin [ https://github.com/asciidisco/Backbone.rpc ] I am attempting to send parameters on the read method when fetching a collection. When working with a single model instance you can add parameters to a method call by setting the value of a model attribute.
var deviceModel = Backbone.model.extend({
url: 'path/to/rpc/handler',
rpc: new Backbone.Rpc(),
methods: {
read: ['getModelData', 'id']
}
});
deviceModel.set({id: 14});
deviceModel.fetch(); // Calls 'read'
// Request created by the 'read' call
{"jsonrpc":"2.0","method":"getModelData","id":"1331724849298","params":["14"]};
There is no corresponding way that I am aware of, to do a similar thing prior to fetching a collection as there is no 'set' method available to backbone collections.
var deviceCollection = Backbone.collection.extend({
model: deviceModel,
url: 'path/to/rpc/handler',
rpc: new Backbone.Rpc(),
methods: {
read: ['getDevices', 'deviceTypeId']
}
});
// This is not allowed, possible work arounds?
deviceCollection.set('deviceTypeId', 2);
deviceCollection.fetch();
// Request created by the 'read' call
{"jsonrpc":"2.0","method":"getDevices","id":"1331724849298","params":["2"]};
Is it possible to pass parameters to collection methods using Backbone.Rpc? Or do I need to pass collection filters in the data object of the fetch method?
I updated Backbone.Rpc (v 0.1.2) & now you can use the following syntax to add "dynamic"
arguments to your calls.
var Devices = Backbone.Collection.extend({
url: 'path/to/my/rpc/handler',
namespace: 'MeNotJava',
rpc: new Backbone.Rpc(),
model: Device,
arg1: 'hello',
arg2: function () { return 'world' },
methods: {
read : ['getDevices', 'arg1', 'arg2', 'arg3']
}
});
var devices = new Devices();
devices.fetch();
This call results in the following RPC request:
{"jsonrpc":"2.0","method":"MeNotJava/getDevices","id":"1331724850010","params":["hello", "world", "arg3"]}
Ah,
okay, this is not included at the moment, but i can understand the issue here.
I should be able to add a workaround for collections which allows the RPC plugin to read
collection properties.
var deviceCollection = Backbone.collection.extend({
model: deviceModel,
url: 'path/to/rpc/handler',
rpc: new Backbone.Rpc(),
deviceTypeId: 2,
methods: {
read: ['getDevices', 'deviceTypeId']
}
});
Which will then create this response:
{"jsonrpc":"2.0","method":"getDevices","id":"1331724849298","params":["2"]};
I will take a look this evening.