knockout binding for simple object not working - javascript

I can make knockout work for array or simple object but not for a simple json object.
Can someone provide pointers plz.
http://jsfiddle.net/aECM9/
html:
<table>
<tbody>
<tr><td>customer Number: </td><td data-bind="text: customerData().reference"></td></tr>
<tr><td>customer Name: </td><td data-bind="text: customerData().name"></td></tr>
<tr><td>customer Manager Code: </td><td data-bind="text: customerData().managerCode"></td></tr>
</tbody>
</table>
javascript:
var viewModel = {
customerData: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.customerData({
reference: 123,
name: "bob",
managerCode: 321
});

Look at the console. When you call applyBindings it throws an error because it tries to access customerData().reference but customerData() is undefined at this point. Move your .applyBindings below where you assign the customerData value.
See: http://jsfiddle.net/aECM9/2/
Another alternative would be to use an if binding to stop knockout from trying to bind properties on customerData() before it has a value:
<tbody data-bind="if: customerData()">
Now nothing after this to the closing </tbody> tag will be rendered if customerData() is falsy.
http://jsfiddle.net/aECM9/3/
I used tbody, but you could use any appropriate parent tag or even a virtual tag:
<!-- ko if: customerData() -->

Related

Knockout TypeScript table not rendering data

I have a table, which shows invoices, then a nested table that shows the individual checks made for those invoices. I'm using knockout and typescript to render these tables. I am able to get the invoices to show, however the checks table doesn't show the data. Here's the code so far:
<tbody class="nohighlight" data-bind="foreach: parent.bankDrafts">
<tr>
<td><span data-bind="text: CheckID"></span></td>
<td><span data-bind="text: CheckRunID"></span></td>
<td><span data-bind="text: VendorName"></span></td>
<td><span data-bind="text: CheckDate"></span></td>
<td><span data-bind="text: FormatCurrency(CheckAmount)"></span></td>
<td><span data-bind="text: Globalize.formatCheckRunApproveStatus(ApprovalStatusID)"></span></td>
</tr>
</tbody>
Here's the typescript:
namespace CheckRunApproval {
declare let searchParameter: string;
class SearchCheckRunModel {
public searchParameter = ko.observable<string>(searchParameter || null);
public checkRuns = ko.observableArray<CheckRunModel>(null);
public bankDrafts = ko.observableArray<BankDraftInfoModel>();
}
var model = new SearchCheckRunModel();
export function GetBankDrafts(data: CheckRunModel): void {
CheckRunServiceMethods.GetBankDrafts(data.CheckRunID())
.done(bankDrafts => ko.mapping.fromJS(bankDrafts, null, model.bankDrafts));
}
}
And here's the service call:
public static GetBankDrafts(checkrunID: number): JQueryPromise<BankDraftInfo[]> {
return CommonMethods.doAjax<BankDraftInfo[]>(
"/Corp/Checks/CheckRunApprovalWS.asmx/getBankDrafts",
JSON.stringify({ checkrunID }),
"GetBankDrafts"
);
}
Now the server call does reach the server side code, passing in the correct parameters and returning the list of checks I'm trying to show as part of the invoice. However, the table itself does not have any data.
My thinking is that it has something to do with the way I'm mapping the model to the view model. It could also be the way I've setup the table itself, with the correct knockout attributes, etc. Any help would be greatly appreciated.
Edit: changing parent.bankDrafts to $parent.bankDrafts() it fixed the issue.
You have a typo in your code. Use $parent.bankDrafts instead of parent.bankDrafts in a foreach binding.

Populate knockout view model from javascript

I'm in the process of replacing one hell of a lot of javascript/jquery code with knockoutjs and I'm trying to figure out the best way forward. I have no time to replace everything at the same time so I will have to integrate the knockout logic with the existing javascript...
Is there a way to populate a knockout view model from javascript which is not called from a data-bind attribute? Any help would be nice since I've not been able to find this anywhere else (at least not anything that worked).
I know what I'm mentioning here isn't the "correct" way of doing things, but I'm trying to migrate parts of the javascript code... Doing it all in one go isn't an option at the moment.
(using knockout 3.2)
Edit:
Typically the existing javascript does something like:
$('#productlist').append(productItemHtmlCode);
And I would rather have it do something like:
ViewModel.productList.push(productItemObject);
If I understand correctly, currently you have something like this:
<div id='myDiv'>
current status is: <span id='statusSpan'>Active</span>
</div>
with some corresponding javascript that might be something like:
function toggleStatus() {
var s= document.getElementById('statusSpan');
s.innerHTML = s.innerHTML == 'Active' ? 'Inactive' : 'Active';
}
And you want to change it so that the javascript is updating the viewmodel rather than manipulating the DOM?
var app = (function() {
var vm = {
statusText: ko.observable('Active'),
toggleStatus: toggleStatus
}
return vm
function toggleStatus() {
vm.statusText = vm.statusText == 'Active' ? 'Inactive' : 'Active';
}
}) ();
ko.applyBindings(app,document.getElementById('myDiv'));
And then the html would be
<div id='myDiv'>
current status is: <span id='statusSpan' data-bind="text: statusText"></span>
</div>
If that's what you're talking about, that's what Knockout is designed for. The javascript updates the viewmodel, knockout manipulates the DOM.
The example you give is easy to represent in Knockout.
the HTML:
<div>
<table data-bind="foreach: products">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: category"></td>
</tr>
</table>
</div>
and in the viewmodel:
vm = {
products: ko.observableArray(), // empty array to start
addProduct: addProduct
}
return vm;
function addProduct(id, name, category) {
products.push({id: id, name: name, category:category});
}
etc.

Values not updating when using functions to assign templates

I have this HTML and am trying to use it to generate a table with the option to add more rows:
<thead>
<tr>
<th>Item</th>
<th>Cost</th>
<th>Amount</th>
<th>
<button class="btn btn-default" data-bind="click: addItem">Add Item</button>
</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="template: {name: $parent.dynTemplate, data: item }">
<td data-bind="template: {name: $parent.dynTemplate, data: cost() }"></td>
<td data-bind="template: {name: $parent.dynTemplate, data: amount() }">
<td></td>
</tr>
</tbody>
I'm using two different templates:
<script id="inpTmp" type="text/html">
<input data-bind="value: $data" />
</script>
<script id="dispTmp" type="text/html">
<p data-bind="text: $data"></p>
</script>
and am choosing which one to call based on the results of the dynTemplate function. The knockout that I have powering this is very simple:
function ItemAdd(name, icost, iamount) {
var self = this;
self.item = name;
self.cost = ko.observable(icost);
self.amount = ko.observable(iamount);
}
function TestModel() {
var self= this;
self.items= ko.observableArray([
new ItemAdd("a", 5, 10),
new ItemAdd("b", 6, 4)
]);
self.addItem= function() {
self.items.push(new ItemAdd("", 0, 0));
};
self.dynTemplate= function(init, s) {
if(init=== 0 || init=== '') {
return 'inpTmp';
}
return 'dispTmp';
};
}
ko.applyBindings(new TestModel());
The problem that I am running into is that when I enter values into newly created rows, the values in items do not change. They initialize properly, but when I run a function to log the values in items they stay as their defaults. If I use knockout if statements, then everything updates properly. However, using 6 sets of if statements didn't seem very effective so I wanted to see if I could pull it out into a function and then send back the proper template. I'm trying to have inputs there when the value is "" or 0, and then change them to <p> when something is entered.
I've tried changing how the data is passed into the template, and I've tried to assign context using with, but to no avail. Calling dynTemplate does not work unless prefixed by $root or $parent. If that is changing the context, is there a way to reset it?
Is this a problem of context, and if so, is there a way to assign context with the dynTemplate function? Or are the newly created elements from the template not properly binding? I've searched quite a bit, and have found templates within foreach loops, but have not seen functions being used to apply them. If there is a better way to do this, please let me know.
Thank you for the help
Your current sample doesn't work because ko dependency tacker doesn't see that your model field is changed. It happens because 'init' is unwrapped value (not an observable).
This fiddle shows how to make it work with single 'item' field.
http://jsfiddle.net/tabalinas/VXXqr/
In this changed version of dynTemplate we get the value of observable, and thus dependency tracker can see that value changed. Of course, we need to change the template.
self.dynTemplate= function(item, s) {
var val = item.item();
if(val=== 0 || val=== '') {
return 'inpTmp';
}
return 'dispTmp';
};
<script id="inpTmp" type="text/html">
<input data-bind="value: $data.item" />
</script>
<script id="dispTmp" type="text/html">
<p data-bind="text: $data.item"></p>
</script>
For your case, where you need universal template for all fields you can do the following: pass as data the name of the field. The template will pick up data from $parent. dynTemplate func is changed accordingly.
<tbody data-bind="foreach: items">
<tr>
<td data-bind="template: {name: $parent.dynTemplate, data: 'item' }">
</td>
<td data-bind="template: {name: $parent.dynTemplate, data: 'cost' }">
</td>
<td data-bind="template: {name: $parent.dynTemplate, data: 'amount' }">
</td>
</tr>
</tbody>
<script id="inpTmp" type="text/html">
<input data-bind="value: $parent[$data]" />
</script>
<script id="dispTmp" type="text/html">
<p data-bind="text: $parent[$data]"></p>
</script>
self.dynTemplate= function(field, context) {
var value = context.$parent[field]();
if(value=== 0 || value=== '') {
return 'inpTmp';
}
return 'dispTmp';
};
See fiddle http://jsfiddle.net/tabalinas/VXXqr/5/

Display an images using data-bind knockout.js

I am working on a table for a web application using MVC and knockout.js. I have experience doing web development but this is my first time using knockout. I currently have a table with 3 columns. The 2nd and 3rd are populated using a knockout function that displays the data. I tried to set up the first column the same way except using an image instead of text. I keep getting a broken image icon and an error in the brower's console.
The error the browser is giving me:
GET http://hostinfo/Sponsor/~PracticeAppImagesGWC.png 404 (Not Found)
This is my table:
<table id="sponsorTable">
<thead><tr>
<th></th><th id="sponsor">Sponsor</th><th id="description">Description</th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: Sponsors">
<tr>
<td><img data-bind="attr: {src: Image}" /></td>
<td class="sTableInfo" data-bind="text: Name"></td>
<td class="sTableInfo" data-bind="text: Description"></td>
</tr>
</tbody>
</table>
This is my function for filling the table. (columns 2 and 3 fill properly)
function pageModel() {
var self = this;
self.Sponsors = ko.observableArray([]);
}
function Sponsor( _image, _name, _descrip)
{
var self = this;
self.Image = ko.observable(_image);
self.Name = ko.observable(_name);
self.Description = ko.observable(_descrip);
}
var viewModel = new pageModel();
viewModel.Sponsors().push(new Sponsor("~/Images/GWC.png", "name1", "info1"));
viewModel.Sponsors().push(new Sponsor("second image would go here", "name2", "info2"));
$(function () {
ko.applyBindings(viewModel);
})
I think something is escaping the slashes in the img source link, but I'm not sure and I can't figure out why.
UPDATE: my compiler is telling me this for the image tag: "Validation (HTML5): Element 'img' is missing required attribute 'src'."
The pushmust be on the observableArray itself, you need to remove the parenthesis:
var viewModel = new pageModel();
viewModel.Sponsors.push(new Sponsor("~/Images/GWC.png", "name1", "info1"));
viewModel.Sponsors.push(new Sponsor("second image would go here", "name2", "info2"));
Pass just image name from viewmodel, and static folder path can be append like this.
// in viewmodel
viewModel.Sponsors().push(new Sponsor("GWC.png", "name1", "info1"));
// inside table
<td><img data-bind="attr: {src:'/Image/'+ Image}" /></td>
Hope this helps...

Accessing object fields in observable array of objects. KnockoutJS

I have a table, that is filled through data-binds with data from observable array of objects (persons). When i click a certain cell of table, index of a line, and index of a cell is written into variables "self.currentLine" and "self.currentCell", while input appears above with 100% width and 100% height, covering that data with itself.
Is there a possibility to get access to certain field of certain object in observable array, using only indexes of fields instead of using field names? (ex. not self.persons[0]'name', but self.persons[0][0])
Here is a code(JS):
function person(fullname, age, sex, married)
{
this.name = ko.observable(fullname); //string, only observable field, while i'm trying to get this working properly.
this.age = age; //Data
this.sex = sex; //string
this.married = married; //bool
};
function personViewModel()
{
var self = this;
self.currentLine = ko.observable();
self.currentCell = ko.observable();
self.columnNames = ko.observableArray([
'Name',
'Age',
'Sex',
'Married'
]);
self.persons = ko.observableArray([...]);
};
self.setLine = function(index)
{
self.currentLine(index);
};
self.setCell= function(cellIndex)
{
self.currentCell(cellIndex);
};
};
ko.applyBindings(new personViewModel());
And HTML code i use:
<table>
<thead data-bind="template: { name: 'tableHeader', data: columnNames }" />
<tbody data-bind="template: { name: 'tableContent', foreach: persons }" />
</table>
<script id="tableHeader" type="text/html">
<tr data-bind="foreach: $data">
<td data-bind="text: $data,
css: { 'active': $root.currentItem() == $data }">
</td>
</tr>
</script>
<script id="tableContent" type="text/html">
<tr data-bind="click: $root.setLine.bind($data, $index())">
<td data-bind="click: $root.setCell.bind($data, $element.cellIndex)">
<span data-bind="text: name"></span>
<input type="text" data-bind="visible: $root.currentCell() == 0 && $index() == $root.currentLine(),
value: name"/> <!--fixed-->
</td>
</tr>
</script>
In html i set input visible according to cell clicked in the table. So now i need to pass a value of a cell to an input, so i could edit this data.
UPDATE: as usual, i've forgot to put round brackets '()' after value: name() in input. But here comes second question. As i know value must be automaticly changed while input loses his focus. But mine doesn't change...
Use the input value binding to to pass a value of a cell:
AFAIK, there is no way to access a field with its supposed index, to read a field from an object in observableArray you may use this syntax :
persons()[index].fieldName(), given that the field is observable also.
hope it help.

Categories

Resources