Data not being fetched from json file - json

I am trying to fetch data from the static json file but the data is not getting displayed at all. What could be the possible reason for it.
Below is my code:
var Collection = Backbone.Collection.extend({
url: "names_of_people.json",
initialize: function() {
this.fetch();
}
});
collections = new Collection();
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}

The problem is that this code:
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
ends up being executed before this.fetch() has completed. You'll need to either put your code in this.fetch's success callback, like this:
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.fetch({
success: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
}
});
var collections = new Collection();
or by listening to the collection's sync event, which occurs when this.fetch has completed successfully. This pattern is more commonly used in Backbone applications.
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.listenTo(this, 'sync', this.syncExample);
this.fetch();
},
syncExample: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
var collections = new Collection();
You can read more about Backbone's event system and the listenTo function here.

check backbone parse function. after fetch it will also call vlidate and parse if they exist.
EDIT: more detail
The key thing here I think is, the fetch() is asynchronous, so by the time you start loop, the data is not here yet. So you need to execute the code when you are sure the collection is ready. I usually listen to a "reset" event, and let the fetch to fire a reset event by collection.fetch({reset:true}).
Backbone Collection, whenever fetch, and get an array of data from server in a format
[obj1,obj2],
it will pass each of these into a parse function, described here
For debug purpose you can simply do:
var MyCollection=Backbone.Collection.extend({
parse:function(response){
console.log(response);
return response;
}
})
This can check if the fetch indeed get the json.
On a side note, it is always a good practise to fetch it after you initialized the collection, means you don't put the this.fetch() inside initialize(), you do this outside.
for example, if you want to print out all the element name, you can do
var c=MyCollection();
c.fetch({reset:true}); // this will fire 'reset' event after fetch
c.on('reset',printstuff());
function printstuff(){
_.forEach(c,function(e){
console.log(e.get('name'));
});
}
Note this 'reset' event fires after all the collection is set, means it is after the parse() function. Apart from this parse(), there is also a validate function that is called by model. You collection must have a model parameter, you can make your own model, and give it a validate(), it also print out stuff.

Related

AngularJS : get back data from a json array with an id

I have a json file where i am stocking informations from all the people in my database. I actually use it to display first name, last name in a web page and i want to add the possibility to display the details of every person.
To do so i'm using the id of the person like this :
.when('/people/:id', {templateUrl: 'partials/people-detail.html'})
It works pretty well, i have a page generated for every person, which is nice. But now I would like to get the information of the person back.
The easiest way would have been to have a json file for every person, but i don't particularly like the idea of having so much file.
So my actual idea is to iterate through the people.json file to find the good one and using it but it's not working.
Here's my controller :
var PeopleController = angular.module ('PeopleController', []);
PeopleController.controller('PeopleDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.search = function() {
var url = 'data/people.json';
$http.get(url).success(httpSuccess).error(function() {
alert('Unable to get back informations :( ');
});
}
httpSuccess = function(response) {
$scope.persons = response;
}
function getById(arr, id) {
for (var d = 0, len = arr.length; d < len; d += 1) {
if (arr[d].id === id) {
return arr[d];
}
}
}
$scope.search();
$scope.person = getById($scope.persons,$routeParams.id);
}]);
Well, maybe my solution is bad since it doesn't work, but i didn't find another way to do so.
Now i'm all yours :)
Thanks for reading.
The problem is that your $scope.search method contains $http.get() which is asynchronous.
What that means is your next line (the one that sets $scope.person) executes before the json file has been read. As such, $scope.persons is empty at the time it is executed.
You can take advantage of the fact that $http.get() returns a chainable promise here.
So if you change your search() function to return that promise, you can then use then() to populate person when everything has been successful:
$scope.search = function() {
var url = 'data/people.json';
return $http.get(url).success(httpSuccess).error(function() {
alert('Unable to get back informations :( ');
});
}
(note the return statement).
Then change the person population to take advantage of this:
$scope.search().then(function(){
$scope.person = getById($scope.persons,$routeParams.id);
});
I hope getting a person is a whole different event like on click. You can try grep:
$scope.person = function(_id) {
return $.grep($scope.persons, function(item){
return item.id == _id
})[0];
}
Assuming you have all persons available otherwise this logic has to move inside the part of the success callback for the http call.
I used ECMAScript 5 filter to get person by id and moved your search by id to success method since we are dealing with ajax call.
Example:
app.controller('PeopleDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.search = function() {
var url = 'data.json';
$http.get(url).success(httpSuccess).error(function() {
alert('Unable to get back informations :( ');
});
}
httpSuccess = function(response) {
$scope.persons = angular.fromJson(response);
$scope.person = $scope.persons.filter(function(item){
return item.id==routeParams.id //check for undefined;
});
}
$scope.search();
}]);
Live Example: http://plnkr.co/edit/jPT6aC5UqLdHGJ1Clfkg?p=preview

Where do I define context (JSON object) when creating a Handlebars.registerHelper in a Backbone View?

I do not know where to define the context (JSON object) in a Handlebars.registerHelper function in a Backbone View.
I am able to render my helper function data in the console when I access it through $.getJSON, but I cannot get the data from the helper function into my template:
var SurveyView = Backbone.View.extend({
template: Handlebars.compile(
'<ul>' +
'{{#each models}}<h3>{{attributes.name}}</h3><h4>{{attributes.question}}</h4>'+
'<li>{{#answerList info}} {{{answers}}}{{/answerList}}</li>{{/each}}' +
'</ul>' +
'<button type="button" class="btn btn-danger">Next</button>' +
),
helperOne: function() {
Handlebars.registerHelper('answerList', function(context, options) {
var output = "";
$.getJSON('questions', function(info) {
for (var i = 0; i<info.length; i++ ){
var infos = info[i];
for (key in infos.answers) {
if(infos.answers.hasOwnProperty(key)) {
output += '<li>' +
'">' + info[i].answers[key] +
'</li>';
console.log(output);
}
}
}
});
return output;
}); //end register
},
initialize: function() {
this.listenTo(this.collection, "reset", this.render);
},
render: function () {
this.helperOne();
this.$el.html(this.template(this.collection));
return this;
}
});
Trying to do an AJAX call inside a Handlebars helper isn't a very productive thing to do. The helper only knows about text: the helper returns a piece of text that will probably become a set of DOM nodes but there is no way for the helper to know what the DOM nodes are so it can't update anything on the page when the AJAX call returns from the server.
You need to turn your logic around:
Figure out what AJAX calls need to be made.
Perform the AJAX calls.
When all the AJAX calls have finished, collect up the data for the template and hand it to the compiled template function.
Add the template function's return value to the DOM.
In your case, you can get rid of helperOne completely. Then, presumably you'd have an Answer Backbone model and an AnswerList collection which contains Answers. Somewhere you'd do a fetch on the AnswerList and when that returns, you can update your view.

Custom binding to return the last Json record

I'm using the following code to load all Json data.
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
});
I also need to load a single record from the same Json data; the record with the highest SortedListsID value (i.e. the last record entered).
Can anybody suggest the best way to do this? I've considered adding viewModel.lastsortedlist and amending the above code somehow. I've also considered creating a last custom binding to do something like:
<tbody data-bind="last: sortedlists.SortedListID">
All advice welcome.
Unless you want to do more ui-related stuff with the record, I don't think you need the custom binding.
It should be enough to compute it in the getJSON callback and save it in the viewModel:
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
//correct the sort function if it's bad, or drop it if allData is already sorted
var sortedData = allData.sort(function(a,b){ return a.SortedListID - b.SortedListID})
viewModel.lastSortedList(sortedData[sortedData.length - 1])
});
Or, if it can change outside the getJSON callback, you could also make it a computed observable:
viewModel.lastSortedList = ko.computed(function(){
//correct the sort function if it's bad, or drop it
var sortedData = mappedSortedLists().sort(function(a,b){ return a.SortedListID - b.SortedListID})
return sortedData[sortedData.length - 1]
}, this)

How to get a value of a property in JSON array from extjs store?

I have been trying to dynamically generate a check box from a value which is in JSON array from a JSON store.
{"MODULECATOGERY":[{"Menu":"MSU"},{"Menu":"SCHEDULE"},{"Menu":"MARKET_DASHBOARD"},{"Menu":"FE_REFERENCE"},{"Menu":"QC_TOOLS"},{"Menu":"QUICKQC_VOICE"},{"Menu":"QUICKQC_DATA"},{"Menu":"MARKETQC_VOICE"},{"Menu":"MARKETQC_DATA"},{"Menu":"SURGERY"},{"Menu":"FILE_INVENTORY"},{"Menu":"MARKET_TRACKER"},{"Menu":"DRIVE_ROUTE_TRACKER"},{"Menu":"TICKETS"},{"Menu":"TICKET_TRACKER"},{"Menu":"ASSETS"},{"Menu":"METRICS"},{"Menu":"DAILY_STATUS"},{"Menu":"DAILY_PROCESSING"},{"Menu":"WEEKLY_WORKFLOW"},{"Menu":"CUSTOMER_QUESTIONS"},{"Menu":"KPI_PERFORMANCE_METRICS"},{"Menu":"COLLECTION_METRICS"},{"Menu":"OPERATIONS_DASHBOARD"},{"Menu":"PRODUCTION_DASHBOARD"},{"Menu":"SUPPORT_DASHBOARD"},{"Menu":"REVENUE_TRACKER"},{"Menu":"DEPLOYMENT_TRACKER"},{"Menu":"TICKETS"},{"Menu":"TICKET_TRACKER"},{"Menu":"ASSET_MANAGEMENT"},{"Menu":"GENERATE_SHIPMENT"},{"Menu":"SHIPMENT_TRACKER"},{"Menu":"RESOURCES"},{"Menu":"SCHEDULE"},{"Menu":"TRACKER"}]}
How can a get values associated with "Menu" in the above JSON.? If i can have each and every value into an array then i can dynamically assign these to generate a check box group.
Thanks in Advance.
You can iterate your store:
store.each(function(record) {
var menu = record.get('Menu');
});
Edit:
Since you're saying this doesn't work with dynamic data I think you iterate it before it has completed loading. To be sure to handle the iteration after the load you can do the following:
store.on({
//Listener that fires everytime after your store has loaded
load: function() {
store.each(function(record) {
var menu = record.get('Menu');
//do stuff
});
}
});
store.load();
If you only want to execute the code the first time your store loads you can use the callback function on the load() method:
store.load(function() {
store.each(function(record) {
var menu = record.get('Menu');
//do stuff
});
});

HTML FileReader

function fileSelected() {
// get selected file element
var files = document.getElementById('files[]').files;
for (var i = 0; i < files.length; i++) //for multiple files
{
(function (file) {
var fileObj = {
Size: bytesToSize(file.size),
Type: file.type,
Name: file.name,
Data: null
};
var reader = new window.FileReader();
reader.onload = function (e) {
fileObj.Data = e.target.result;
};
// read selected file as DataURL
reader.readAsDataURL(file);
//Create Item
CreateFileUploadItem(fileObj);
})(files[i]);
}
}
function CreateFileUploadItem (item) {
console.log(item);
$('<li>', {
"class": item.Type,
"data-file": item.Data,
"html": item.Name + ' ' + item.Size
}).appendTo($('#filesForUpload'));
}
So when console.log(item) gets run in the CreateFileUploadItem function it shows the item.Data. YET it won't add it to the data-file of the LI. Why is that?
The call to readAsDataURL is asynchronous. Thus, the function call is likely returning prior to the onload function being called. So, the value of fileObj.Data is still null when you are attempting to use it in CreateFileUploadItem.
To fix it, you should move the call to CreateFileUploadItem into your onload function. As for the console logging the proper value, you can't rely on that being synchronous either. I think using a breakpoint during debugging at that line instead will likely show the true null value.