Salve galera,
Outro dia precisei sobreescrever o toJSON do Backbone Model.. fica ai a dica de como fazer
// method override
toJSON: function () {
if (this.beforePost)
this.beforePost();
// call the "super" method
var json = Backbone.Model.prototype.toJSON.call(this);
// here manipule the json objeto ;)
return json;
}
Eu precisava alterar o comportamento para que, quando fosse criado um objeto para o post, alguns atributos mudassem de nome no json, assim:
// mapper properties to swap values
properiesMap: [
{ from: 'TaskGroup', to: 'TaskGroupId' },
{ from: 'TaskType', to: 'TaskTypeId' },
{ from: 'UserProfile', to: 'UserProfileId' },
{ from: 'Sprint', to: 'SprintId' },
{ from: 'BacklogItem', to: 'BacklogItemId' },
{ from: 'Status', to: 'Status' },
],
// call before json creation
beforePost: function() {
this.attributes['Content'] = $(".form-task").find("[name='Content']").val();
this.attributes['BacklogItem'].Id = parseInt($("#backlogItemId").val());
},
// call to create json to post
toPostJson: function () {
if (this.beforePost)
this.beforePost();
// the original toJSON
var json = Backbone.Model.prototype.toJSON.call(this);
for (var i = 0; i < this.properiesMap.length; i++) {
var it = this.properiesMap[i];
json[it.to] = this.get(it.from).Id;
if (it.from != it.to)
delete json[it.from];
}
return json;
}