Gerben Wiersma
Gerben Wiersma

Reputation: 41

BackBone model ToJSON renders a field to zero

I have some strange behavior in my model. When I was debugging with this code something strange emerged:

console.log(this.model);
console.log(this.model.toJSON());

These 2 lines offer two different results. The log of this.model

attributes: Object
   distance: "6500"
   duration: "25:17.1"
   id: "33"
   intervalid: "1"
   pace: "1:56.7"
   rowdate: "2012-03-08 20:47:36"
   trainingid: "18"

And then the log of the toJSON()

Object
   distance: "6500"
   duration: "0"
   id: "33"
   intervalid: "1"
   pace: "1:56.7"
   rowdate: "2012-03-08 20:47:36"
   trainingid: "18" 

Does anybody have a clue why my duration field is reduced to 0? And a way to prevent toJSON() from changing duration to 0?

Upvotes: 0

Views: 283

Answers (1)

biziclop
biziclop

Reputation: 14616

Works for me, even when I set duration: String("25:17.1"):

http://jsfiddle.net/m4eeU/

Model.toJSON source:

toJSON: function() {
  return _.clone(this.attributes);
},

Underscore source:

// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
  if (!_.isObject(obj)) return obj;
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};

Upvotes: 1

Related Questions