I have a backbone setup for Workflows. There are multiple workflows/models visible on the page at any given time. If a workflow is not started yet (i.e. not in the database), it is displayed as a New model. Having trouble with passing the fetched model to the view. I’m only passing the attributes rather than the collection it seems? Anyone have any ideas?
When I fetch all workflows from the database, it returns a JSON array of workflows progress.
[{
"ref_id": 41959,
"parent_ref_id": 35,
"fk_workflow_id": 2,
"stage": 1,
"status_max": 4,
"updated": "2012-05-14 17:30:46"
}, {
"ref_id": 41960,
"parent_ref_id": 35,
"fk_workflow_id": 3,
"stage": 3,
"status_max": 4,
"updated": "2012-05-14 12:30:48"
}]
When the page is loaded, all workflows are created as “new models”, because we don’t know if they’ve been started yet. Once the fetch has returned the models that have been started, I have to pass the appropriate model to the view. I’m having trouble figuring out how to pass the model properly (i.e. I can pass the attributes, but it seems after that, I don’t have access to the collection.create functions etc?)
var self = this;
this.workflows = new Workflow.WorkflowCollection();
this.workflows.fetch({
data:{
ref_id: REF_ID
},
success: function(model, response) {
for(var i = 0, ln = model.models.length; i< ln;i++) {
self.switchWorkflow(model.models[i].get("fk_workflow_id"), new Workflow(model.models[i].attributes));
}
}
});
This is the only way I can figure backbone knows how many models it needs to setup (short of initiating each of the workflows for each customer – ~1million rows)
setupWorkflowSpaces: function(model) {
for(var i =0; i<Workflow.FileWorkflows.length;i++) {
this.switchWorkflow(Workflow.FileWorkflows[i], false);
}
},
switchWorkflow: function(workflow_id, model) {
if(!model)
model = new Workflow;
switch(workflow_id) {
case 1:
this.applicationProcessView(model);
break;
case 2:
this.kitView(model);
break;
case 3:
this.posView(model);
break;
default:
alert('wut');
break;
}
},
kitView: function(model) {
console.log(model);
model.set("fk_workflow_id", 2);
if(this.kit) this.kit.close();
this.kit = new Workflow.PostageView({
model: model
});
},
Try defining the
modelproperty in your Backbone Collection:If defined, the raw attributes coming back from your server will be converted into a
Workflowmodel.Then you won’t have to iterate through the collection that is returned via the
successcallback infetch. All the added models will be in your collection and you can use the.create()method to continue adding more.After fetch you can iterate through the updated collection using
WorflowCollection.each. In the loop you can run your switch statement to assign the each model to an appropriate view.I hope this helps.