Fetching Data using .getJSON and storing using Knockout.JS - javascript

My TweetModel is setup like this
function TweetModel(tweet) {
var self = this;
this.tweet = ko.observable(tweet);
}
[UPDATED]
Running into trouble binding the solution. For some reason, after the TweetModel object is created, it is not being pushed to self.tweets.
I broke this up into steps...
.getJSON(someurl, function(data){
$.each(data, function (i, val) {
var tweetModel = new TweetModel();
tweetModel.tweet = data.key[0];
self.tweets.push(tweetModel);
//all could be compressed into self.tweets.push(new TweetModel(val));
//Object is being created but self.tweets returns an empty list when debugged
}}
Any help would be appreciated, thanks.

Try this:
$.getJSON(someurl, function (data) {
$.each(data.key, function (i, val) {
self.tweets.push(new TweetModel(val));
}
}

Related

how to remove the chrome.storage.local

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

How to assign array of object to dropdown in angularjs?

Hi I am developing web application in angularjs. I have one html form with several drop downs. I am making api calls to fill data to drop down. Instead of making separate call in one call i am getting all data required to bind all drop downs.
Below is my sample data.
{"status":"Success","msg":"Success","code":"200","data":{"Education":[{"ID":1,"Education":"btech"},{"ID":2,"Education":"Bcom"},{"ID":3,"Education":"BA"},{"ID":6,"Education":"PU"}],"MaritalStatus":[{"ID":1,"MaritalStatus":"sinle"},{"ID":2,"MaritalStatus":"married"}]}
I am trying to bind it to drop down as below.
var martialstatus = new Array();
var Education = new Array();
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
$.map(data.data, function (item) {
Education.push(item[0]);
});
console.log(Education);
}).error(function (status) {
});
Abobe piece of code gets me first item from the each object like first item from education,martial status etc. I would like to bind education object to education array. May i know where i am missing any line of code? Any help would be appreciated.
You don't seem to do any kind of mapping from the original result, so the following would suffice:
Education = data.data.Education;
Note:
The item[0] looks strange - are you trying to achieve something with that ?
I would use lowercase for the name of the variable.
Try something like this:
var MaritalStatus = new Array();
var Education = new Array();
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
$.map(data.data.Education, function (item) {
Education.push(item);
});
$.map(data.data.MaritalStatus, function (item) {
MaritalStatus.push(item);
});
}).error(function (error) {
// handle API errors
});
If you do not even need to format the output, you can simply re-assign the original value of your variable.
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function (data) {
Education = data.data.Education;
MaritalStatus = data.data.MaritalStatus;
}).error(function (error) {
// handle API errors
});
You can do it this way:
var martialstatus = new Array();
var Education = [];
$http.get(baseurl + 'api' + '/Customer/' + 'PersonalInfoMasters').success(function(data) {
$.map(data.data.Education, function(item) {
Education.push(item);
});
}).error(function(status) {
});
You just need to push item instead of item[0] in the .map() method so it takes the whole Education object and push it in your array.
Otherwise you can just use with no need to use the $.map():
Education = data.data.Education
Shouldn't it be more like:
$.map(data.data.Education, function (item) {
Education.push(item[0]);
});
?

jQuery: Get first object in array after Ajax call

I'm trying to get the first object returned by the ajax call before doing the each() loop through it. Here's the code that works for the each:
$.each(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
What I'd like to do is this:
$.each.first(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
But I'm getting this error:
VM1172:38 Uncaught TypeError: $.each.first is not a function
doing a $.get(obj.DATA)..... doesn't work either.
$.each.first(obj.DATA[0], function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});

Knockout Check If Existing in observableArray before Push

I am new to Knockout and I have a little problem stopping me from completing my simple project.I have an observableArray called loanDeductions that I display in a table with foreach binding. I have another observableArray called loanDeductionsList which is also from the json data of my first observableArray, I used it in my drop down list which when a value is selected, it will push the selected data to my table. If it didn't make sense as I cannot really explain it clearly, this is my javascript file:
var deductionLine = function (deductionID, deductionName, amount) {
self = this;
self.deductionID = ko.observable(deductionID);
self.deductionName = ko.observable(deductionName);
self.amount = ko.observable(formatCurrency(amount));
};
function LoanDeductions(deductions) {
var self = this;
self.loanDeductions = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
self.loanDeductionsList = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
self.selectedDeduction = ko.observable();
self.selectedDeduction.subscribe(function (data) {
self.loanDeductions.push({
deductionID: data.deductionID,
deductionName: data.deductionName,
amount: data.amount,
});
});
}
Can you help me find a way to make my function selectedDeduction.subscribe() push the data ONLY when the item to be pushed is not existing in my loanDeductions observableArray.
Any help will be greatly appreciated. Thank you!
I am somewhat aware that the way I populate my dropdown list may o may not be the best way to do it, I am open to suggestion of a better way and rewrite my program.
just to share what I did I added this line in my selectedDeduction.subscribe():
self.selectedDeduction.subscribe(function (data) {
var match = ko.utils.arrayFirst(self.loanDeductions(), function(deduction) {
return deduction.deductionID() === data.deductionID();
});
if (match) {
alert(data.deductionName() + ' already exists!');
} else {
self.loanDeductions.push({
deductionID: data.deductionID,
deductionName: data.deductionName,
amount: data.amount,
});
}
});

Multidimensional Arrays and jQuery's getJSON

I am submitted a getJSON request to a controller in my application, this controller is returning valid JSON with 2 "applications." I know this for a fact as if I move the alert statement to within jQuery's each function it will give me the expected result.
I am attempting to store this data within a multidimensional array to later be used with extJS' Menu Control.
Code:
Ext.onReady(function() {
var applicationList = [];
jQuery.getJSON('index.php/applications', function(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
});
alert(applicationList[0]['text']);
var applicationMenu = Ext.menu.Menu({
items: applicationList
});
});
JSON Response:
{"applications":[{"slug":"test","title":"Test"},{"slug":"hardware","title":"Hardware"}]}
Expected Result:
Test
Actual Result (from Firebug):
applicationList[0] is undefined
If I replace the alert() above, with the following code I get one alert window with the text "remove":
for (p in applicationList) {
alert(p);
}
Now, my thinking is that the JSON request isn't completing in-time for the alert() so I'll use a named callback function to ensure the request has completed:
var data;
jQuery.getJSON('index.php/applications', get_applications(data));
function get_applications(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
};
But now Firebug is telling me that data is undefined...
I feel like I am almost there, but I've been almost there for the past hour and I feel as if I am just polluting the source now in trying to get it to work.
This should do it:
Ext.onReady(function() {
var applicationList = [];
var applicationMenu;
jQuery.getJSON('index.php/applications', function(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
applicationMenu = Ext.menu.Menu({
items: applicationList
});
});
});
Your thinking is right; the reason it is not working is because AJAX is an asynchronous process and as you fire off the getJSON function javascript keeps on trucking along. Your solution doesn't work because making it a named callback is not changing the fact that it won't be fired until you've already tried to initialize the Menu. All my solution is doing is moving the Menu initilization code INSIDE the callback, as it is then and only then that you will have access to the filled out applicationList.
You're right, you should use your "applicationList" variable only after the getJSON callback has finished.
You should call Ext.menu.Menu() inside your getJSON callback, after jQuery.each().
Paolo Bergantino's solution should work, but you can also do it your way, using a named callback function -- you just made some small errors in your code:
data should not be declared as a variable -- data in "function get_applications(data)" just stands for whatever .getJSON returns
The callback function in .getJSON should just be the name of the function, without (data)
Here's the corrected code:
jQuery.getJSON('index.php/applications', get_applications);
function get_applications(data) {
jQuery.each(data.applications, function (i, app) {
applicationList[i] = [];
applicationList[i]['text'] = app['title'];
applicationList[i]['id'] = app['slug'];
});
};
$.getJSON("getq2.php", {
yr: year,
typ: type
}, function(data) {
var items1 = new Array();
var j = 0;
for (var i in data) {
var items = new Array();
items.push(data[i][0], Number(data[i][1]));
items1[j++] = items;
}
console.log(items1);
var plot1 = jQuery.jqplot('chartContainer', [items1], {
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
startAngle: 180,
sliceMargin: 2,
dataLabelThreshold: 2,
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true,
}
},
grid: {
borderWidth: 0,
shadow: false,
background: '#d8d6cb'
},
legend: {
placement: 'outside',
show: true,
location: 'e',
background: 'transparent',
marginRight: '30px'
}
});
});

Categories

Resources