I am fairly new to knockout and trying to figure out why the following won't work. For some reason my returned data from the ajax call is not being translated into an array.
I have a function that returns some JSON
bankingApi.client = (function () {
var getSafeFloatCash= function getSafeFloatCash() {
return $.ajax({
url: '/BackOffice/Banking/Banking/GetSafeFloat',
type: 'GET'
});
}
return {
getSafeFloatCash : getSafeFloatCash
};
})();
The function returns the following JSON:
[{"Denomination":"1p","Value":34.1200},{"Denomination":"2p","Value":98.0400},{"Denomination":"5p","Value":85.0500},{"Denomination":"10p","Value":571.2000},{"Denomination":"20p","Value":62.8000},{"Denomination":"50p","Value":57.5000},{"Denomination":"£1","Value":441.0000},{"Denomination":"£2","Value":398.0000},{"Denomination":"£5","Value":260.0000},{"Denomination":"£10","Value":320.0000},{"Denomination":"£20","Value":780.0000},{"Denomination":"£50","Value":350.0000}]
I set up my observable array
(function () {
var BankingViewModel = function () {
var self = this;
self.safeFloatDenominations = ko.observableArray();
var safeFloatCash = bankingApi.client.getSafeFloatCash();
self.safeFloatDenominations(safeFloatCash); // does not work!
self.safeTopUpValue = ko.computed(function () {
var total = self.floatRecommendedValue - self.safeFloatTotal;
return total.toFixed(0);
});
}
$(document).ready(function () {
var viewModel = new BankingViewModel();
ko.applyBindings(viewModel);
});
})();
If I paste the values returned from the ajax call into an array variable it works fine, so there is some issue translating the function call into an array.
and this is the view
<div class="row" data-bind="visible: safeTopUpValue()>0, foreach: safeFloatDenominations">
<div class="col-xs-5">
<input type="text" data-bind="value: Value" />
<label data-bind="text: Denomination"></label>
</div>
Building on my comment, $.ajax doesn't return data - it returns a promise. You need to use that to actually get the data out:
var safeFloatCash = bankingApi.client.getSafeFloatCash();
safeFloatCash.done(function(d) {
//may need to parse the data:
//d = JSON.parse(d);
self.safeFloatDenominations(d);
});
Related
I am trying to save the data from the text-boxes to the localStorage using knockout JS! However I am new and not able to figure out this particular scenario. The field has same observable name! Please find my code below.
HTML Code:
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
JS Code:
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
Traget: The data entered inside the text-boxes should be available in localStorage.
You need to define a Handler function to read the data from the Textboxes and save it to the localstorage. You need to reference the Data which is bound to the click event, which can be accessed using the first parameter. Knockout passes the data and event information as 2 arguments to the click handler function. So, you can add the event handler to your viewModel using the click binding and then unwrap the value and save it to localStorage.
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
Complete Code: Please note since this is a sandboxed environment (Running this js Snippet on StackOverflow), localStorage wouldn't work, but it should work in your code. I have added a line in console to get the value to Store.
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
},
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
<button data-bind="click:saveToLocalStorage">Save To local storage</button>
Hi here is a jquery function i am working on i have appended a particular div. The div has 2 inputs I am trying to capture the input values in data_to_send array but it only captures one input because the names are not unique.
function() {
$('#si-goal-link-btn').click(function() {
$('#si-goal-links').append('<div class="goal-link si-goal"><label for="iconURL">Icon URL</label><input class="si-goal-link form-control" type="file" name="iconURL"><br><label for="title">Title</label><input type="text" placeholder="Enter title" class="si-goal-link form-control" name="title"><br><hr></div>')
})
$('form #si-btn').click(function(e) {
e.preventDefault()
var self = $(this)
var data_to_send = {}
$('form').find('.si-input').each(function() {
if ( $(this).attr('name') != undefined) {
if ($(this).hasClass('si-wysiwyg')){
data_to_send[$(this).attr('name')] = $(this).code()
}
if ($(this).hasClass('si-goal-link')) {
//UNABLE TO STORE THE VALUE HERE
data_to_send[$(this).attr('name')] = $(this).val()
}
data_to_send[$(this).attr('name')] = $(this).val()
}
})
var url = $('form').data('si-location')
$.post(url, data_to_send, function(data) {
})
})
}
How do i capture this data and store it as an array within an array over here ?
To get array-within-array-like behavior in Javascript, you will need to make an array a property of your data object, and then push() the same named values onto that array.
var data_to_send = {};
data_to_send.si-goal-link = [];
//inside loop or wherever is needed
data_to_send.si-goal-link.push($(this).val());
$.post(url, $('form').serialize(), function(data) {
})
I am trying to update some radio buttons with knockout js. I retrieve the data from an ajax call similar to this example. Everything works well so far. Data is retrieved and passed to the model. And even the List is generated.
The problem is that jquery is not "skining" the radio list. (Upper part on the image)
Working with a parsed JSON-String everything works fine. (Lower part on the image)
Any ideas?
Thanks
Code:
HTML
<fieldset id="myList" data-role="controlgroup" data-bind="foreach: myVals">
<label data-bind="text:$data, attr: { for:'vals'+$data}"></label>
<input type="radio" data-bind="checked:$root.selectedVals, value:$data ,attr: {name: 'list', id:'vals'+$data}" >
</fieldset>...
JavaScript
// Knockout
function viewModel() {
self = this;
self.myVals = ko.observableArray();
self.selectedVals = ko.observable();
}
var vm = new viewModel();
ko.applyBindings(vm);
// Jquery
$(document).on("pageinit", "#myPage", function() {
$("#autocomplete").on("filterablebeforefilter", function(e, data) {
var $input = $(data.input), value = $input.val();
if (value && value.length > 2) {
$.ajax({
... get data
})
.then(function(response) {
vm.myVals.removeAll(); // clear so results won't add
$.each(response, function(i, val) {
vm.myVals.push(val); // fill Array
});
});
}
});
});
...
Consider this fiddle.
I want to add ko.computeds to a ko.observableArray dynamically:
self.items.push(ko.computed({
read: function () {
return items[i];
},
write: function (value) {
//some write action
alert(value);
}
}));
I need to manage the write function from the ko.computed into the array.
With this code, read works great, but knockout is not calling the write function, so alert is not being called.
Am I missing something? Is there a workaround for this?
I resolved it creating another ViewModel:
function item(value) {
var self = this;
self.value = ko.observable(value);
self.computed = ko.computed({
read: self.value,
write: function (value) {
alert(value);
self.value(value);
}
});
}
function header(items) {
var self = this;
self.items = ko.observableArray();
for (var i = 0; i < items.length; i++) {
self.items.push(new item(items[i]));
}
}
The HTML:
<ul data-bind="foreach: items">
<li>
<input type="text" data-bind="value: computed" />
</li>
</ul>
And the fiddle working.
I'm writing a small application in JS and I decided to use Knockout.
Everything work well except from a single value that is not printed correctly and I don't understand why.
This is the html view where error appends (viaggio.arrivo is not visualized, and in place of correct value appears a function code like this "function c(){if(0 <arguments.length){if ..." and so on)
<input data-bind="value: viaggio.arrivo" />
And this is the javascript View Model.
Code is pretty long so I put it in a jsFiddle.
function ViewModel() {
function Viaggiatore(nome, cognome, eta, citta) {
var self = this;
self.nome = nome; self.cognome = cognome;
self.eta = ko.observable(eta);
self.citta = ko.observable(citta);
}
function Viaggio(viaggiatore, partenza, arrivo, mete) {
var self = this;
self.viaggiatore = ko.computed(viaggiatore);
self.partenza = ko.computed(partenza);
self.arrivo = ko.observable(arrivo);
self.mete = ko.computed(mete);
}
self.viaggiatore = new Viaggiatore("Mario", "Rossi", 35, "Como");
self.viaggio = new Viaggio(
function(){ return self.viaggiatore.nome+" "+self.viaggiatore.cognome; },
function(){ return self.viaggiatore.citta; },
"Roma",
function(){ return "mete" ;}
);
}
ko.applyBindings(new ViewModel());
I think you need brackets on one of your parameters, like so:
<p data-bind="text: viaggio.partenza()"></p>
Check out the updated fiddle: http://jsfiddle.net/mGDwy/2/