Reputation: 1420
I have a collection of models where one field may be null. In that case, I want to display "none" in the list view. However, if the field is not empty I want to display it's contents. Here's my code.
My Model:
App.Models.EventType = App.Helpers.Model.extend(
{
initialize: function(){
console.log('model init');
this.set('etcName', this.get('etcName') === null ? 'none':this.get('etcName'));
},
url : function(){
if(_.isUndefined(this.id)){
return '/api/event_types_controller/event_type';
}
return '/api/event_types_controller/event_type/' + this.id;
}
});
My Collection:
App.Collections.EventTypes = App.Helpers.Collection.extend(
{
initialize: function(){
console.log('collection init');
},
url : '/api/event_types_controller/get_event_types',
model : App.Models.EventType,
sortOrder: 'asc',
sortBy : 'eventTypeName'
}
);
This works for the list view. I see in the console the data is retrieved from the server then the model initialize code runs for each record retrieved. Here is a sample of the JSON returned:
{"eventTypeID":35,"eventTypeName":"DEPO","description":"","instructions":"","lawyersOnly":0,"eventTypeCategoryID":3,"lockedType":1,"etcName":"Deposition"},
{"eventTypeID":34,"eventTypeName":"DENY","description":"Denial","instructions":"","lawyersOnly":0,"eventTypeCategoryID":0,"lockedType":0,"etcName":null}
However, now I need to load an individual record. I know I can put a success: function() in the fetch but it would seem the correct functionality would be consistent before/after data is loaded initialization. No?
From my router:
eventTypesSettingsEdit: function(id){
var eventTypeEditModel = new App.Models.EventType({id: id});
var eventTypeContent = new App.Views.Settings.EditEventType({model: eventTypeEditModel});
App.Helpers.htmlView(eventTypeContent, '#content');
eventTypeEditModel.fetch();
},
In this case, the initialize code of the model executes BEFORE the data is loaded. This seems inconsistent to me. Frankly, I'd expect the init code to run before anything including the fetch of the data and there should be some kind of post fetch initialization where the data can be manipulated.
Can anyone point me in the direction of how to correctly handle the situation where incoming data needs to be modified for both the list and the edit views?
Upvotes: 1
Views: 40
Reputation: 1555
You should use #parse on the model. That is called only when fetching from the server.
http://backbonejs.org/#Model-parse
Upvotes: 1