I am not utilizing Ember Data, and I have integrated an ajax call in my Model to fetch data from a remote source. Once I have successfully retrieved the data from the API, I intend to organize/filter it based on category. My approach is to handle the filtered state of the data through the controller after receiving it from the Model asynchronously.
However, I encounter an issue where the asynchronous nature of fetching data in the Model prevents me from directly calling a method in the controller to sort/filter the data for display in the template.
Below are the relevant sections of my code and a link to my jsfiddle. While iterating over the issue_list
in my template allows me to display the information easily, my goal is to iterate over the categorized_issues
Array. I am unsure when the issue_list
array is actually set so that I can invoke the categorize
method of the IssuesController.
// Default Route for /issues
App.IssuesIndexRoute = Ember.Route.extend({
setupController: function() {
var issues = App.Issue.all(25);
this.controllerFor('issues').processIssues(issues);
}
});
// Model
App.Issue = Ember.Object.extend({});
App.Issue.reopenClass({
// Fetch all issues from the ajax endpoint.
// Won't work on the JS fiddle
all: function() {
var issues = [];
$.ajax({
url: "http://localhost:3000/issues.json",
dataType: 'json',
}).then(function(response) {
response.issues.forEach(function(issue) {
issues.addObject(App.Issue.create(issue));
}, this);
});
return issues;
},
});
// Controller
App.IssuesController = Ember.ArrayController.extend({
issue_list: [],
categorized_issues : {"open":[], "closed": []},
processIssues: function(issues) {
this.set('issue_list', issues);
return issues;
},
categorize: function() {
var self = this;
this.issue_list.forEach(function(i) {
// Based on the issue open or closed status
if (i.status == "open") {
self.categorized_issues["open"].addObject(i);
} else {
self.categorized_issues["closed"].addObject(i);
}
});
},
});
My strategy is as follows:
- Retrieve Data from Model
- Reorganize the data based on its status (open or closed) in the controller
- Present this modified data in the template
However, I am facing difficulties in implementing this. Any suggestions on how to proceed?
DEBUG: -------------------------------
DEBUG: Ember.VERSION : 1.0.0-rc.2
DEBUG: Handlebars.VERSION : 1.0.0-rc.3
DEBUG: jQuery.VERSION : 1.9.1
DEBUG: -------------------------------