Knock Out data binding - html

I have a question about data binding using knockout.
Here's the problem: I have a table, I what I would like to do is that when a row in table is clicked, I want the values of the row to appear in the input fileds which are located above the table.
so here'
<tbody data-bind="foreach: customers">
<tr data-bind="click: doSomething">
<td data-bind="text: date"></td>
<td data-bind="text:staff"></td>
<td data-bind="text: ftype"></td>
<td data-bind="text: value"></td>
<td data-bind="text: message"></td>
</td>
</tr>
</tbody>
In my viewmodel, I have the following function:
doSomething: function(data) {
var self = this;
self.date(data.date);
self.staff(data.staff);
self.ftype(data.ftype);
self.value(data.value);
self.message(data.message);
}
Here's the error I am getting:
["Unable to parse bindings.↵Message: ReferenceError:… is not defined;↵Bindings value: click: doSomething", "views/myView/index", Object]
0: "Unable to parse bindings.↵Message: ReferenceError: doSomething is not defined;↵Bindings value: click: doSomething"
1: "views/myView/index"
2: Object
length: 3
__proto__: Array[0]
Let me know if I need to provide any more details. I will appreciate your help fplks!

A very basic pattern for this type of thing is to have an array of items and a selectedItem observable that you populate when selecting a row.
Then, you can use the with binding around a section to create your editor.
<table>
<tbody data-bind="foreach: customers">
<tr data-bind="click: $root.selectedCustomer">
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
<hr/>
<div data-bind="with: selectedCustomer">
<input data-bind="value: name" />
</div>
Sample: http://jsfiddle.net/rniemeyer/Z6VPV/

You need to bind your model to the view
var currentViewModel = function(){
this.doSomething = function(data){
var self = this;
self.date(data.date);
self.staff(data.staff);
self.ftype(data.ftype);
self.value(data.value);
self.message(data.message);
}
var viewModel = new currentViewModel();
ko.applyBindings(viewModel);

Related

How to bind Knockout model data to Multiple tables

I am using knockout binding to bind some data into html tables. My knockout view Model had multiple products and each product will have multiple chars. I want to display the products in one table and when i select the link "show chars" it should display the corresponding chars in below table.
This is my View Model
var ProductViewModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
And this is my html tables
<div id="productTable">
<table class="ui-responsive table">
<thead>
<tr>
<th >Product Name</th>
<th >Description</th>
<th >Parent?</th>
</tr>
</thead>
<tbody id="pBody" data-bind="foreach: items">
<tr class="success" >
<td><span data-bind="text: name"></span>
</td>
<td><span data-bind="text: desc"></span>
</td>
<td>show chars</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="productChars">
<div id="productCharTable">
<table class="ui-responsive table">
<thead>
<tr>
<th >Char Name</th>
<th >Description</th>
<th >Length</th>
<th >Type</th>
</tr>
</thead>
<tbody id="pBody" data-bind="foreach: $data['chars']">
<tr class="success">
<td><span data-bind="text: name"></span>
</td>
<td>asdf asdfasdf</td>
<td>10</td>
<td>String</td>
</tr>
</tbody>
</table>
</div>
I am able to bind the products into first table. But for characteristics i am not sure how to achieve the same.
Could someone please help me in figuring out how to achieve the same.
Here is the jsfiddle
https://jsfiddle.net/sirisha_k/0Ln7h2bo/7/
As #supercool pointed out you can use "data-bind='with selectedItem'" to populate the second table with chars data. For that you need to add one more item into your model called selectedItem and every time you select or add a row, you point the selectedItem to that elementdata. And use "data-bind='with selecteItem'" for second table.
var ProductViewModel = function(items) {
this.items = ko.observableArray(items);
this.selectedItem = ko.observableArray();
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
and on row select call some function selectedItem($data) where $data refers to the current item.
then set that data to selectedItem in model.
function selectedItem(prod){
ProductViewModel.selectedItem(prod);
}

Knockout.js loop over children of parent in table

My MVVM looks like this:
<script type="text/javascript">
function Company(data) {
this.name = ko.observable(data.name);
this.legal_form = ko.observable(data.legal_form);
this.company_number = ko.observable(data.company_number);
this.type_account = ko.observable(data.type_account);
this.type_supplier = ko.observable(data.type_supplier);
this.type_competitor = ko.observable(data.type_competitor);
this.type_other = ko.observable(data.type_other);
this.children = ko.observableArray(data.child);
}
function CompanyListViewModel() {
// Data
var self = this;
self.companies = ko.observableArray([]);
$.getJSON(Routing.generate('contacts_companies_get_json'), function(allData) {
var mappedCompanies = $.map(allData, function(item) { return new Company(item) });
self.companies(mappedCompanies);
});
}
ko.applyBindings(new CompanyListViewModel());
</script>
My View looks like this:
<tbody data-bind="foreach: companies">
<tr>
<td>
<a href="#" class="title">
<span data-bind="text: name"></span> <span data-bind="text: legal_form"></span>
</a>
</td>
<td data-bind="if:$data.company_number"><span data-bind="text: company_number"></span></td>
<td><span data-bind="if: type_account" ><i class="icon-check"></i></span></td>
<td><span data-bind="if: type_supplier" ><i data-bind="if: type_supplier" class="icon-check"></i></span></td>
<td><span data-bind="if: type_competitor" ><i data-bind="if: type_competitor" class="icon-check"></i></span></td>
<td><span data-bind="if: type_other" ><i data-bind="if: type_other" class="icon-check"></i></span></td>
<td>Details</td>
</tr>
</tbody>
I would like to add hidden <tr> for every child that a parent company has and add a plus sign before the parent to expand the hidden .
The problem is that I can only access the child within the original parent <tr> otherwhise will tell me "children" is not defined.
Any suggestions on how to achieve this?
You can use the foreach without a container element to display the children:
<tbody data-bind="foreach: companies">
<tr>
<!-- company columns -->
</tr>
<!-- ko foreach: children -->
<tr>
<!-- children columns -->
</tr>
<!-- /ko -->
</tody>
And with the help of a new property (like showChildren on the Company) you can do the show hide of the childrens:
Demo JSFiddle.
If you want to display the full hierarcy with the same columns so you want to have to display the children of the child campanies you can achieve with recursive templates.
There were some questions about recursive templates latelly:
Recursive template with knockout js
Working with Knockout 'foreach' looping through multidimensional array

Binding table row with click event

I am using knockout and when I have binded a click event on my table row. However, when I click on the row, it displays the following error:
function d(){if(0<arguments.length){if(!d.equalityComparer||!d.equalityComparer(c,arguments[0]))d.H(),c=arguments[0],d.G();return this}b.r.Wa(d);return c}
does anyone know why I am getting this error?
Here's my view for the table:
<tbody data-bind="foreach: customers">
<tr data-bind="click: $root.doSomething">
<td data-bind="text: date"></td>
<td data-bind="text:staff"></td>
<td data-bind="text: ftype"></td>
<td data-bind="text: value"></td>
<td data-bind="text: message"></td>
</td>
</tr>
</tbody>
Here's my viewmodel:
doSomething: function(data) {
var self = this;
self.date(data.date);
self.staff(data.staff);
self.ftype(data.ftype);
self.value(data.value);
self.message(data.message);
}
Does this do the trick?
<tbody data-bind="foreach: customers">
<tr data-bind="click: function() {$root.doSomething($data);}">

Iterating in JSON using knockout.js

I'm using Knockout.js to realize my web app.
I get data from a database and i use Json to pass data to html page that is rendered through data-bind.
I would like to set the more dynamic possible my app so i would like to iterate through json keys without "hardcoding" the field name
I have the following json: {"id_user":"63","email":"mail#email.it","flag":"1"}
and iterate using:
<table data-bind="foreach:page().users">
<tr>
<td data-bind="text:$data.email"></td>
<td data-bind="text:$data.flag"></td>
</tr>
</table>
but i would like to avoid the .email and .flag and using [0] or [1] to reuse this structure for all the models. How can i do it?
You could do this with a custom binding:
<table data-bind="foreach:page().users">
<tr data-bind="createHeaderRow: $data">
</tr>
<tr data-bind="createTableRow: $data">
</tr>
</table>
Then create these methods:
ko.bindingHandlers.createHeaderRow = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
for (var property in valueAccessor()) {
$(element).append('<td>' + property + '</td>');
}
}
};
ko.bindingHandlers.createTableRow = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
for (var property in valueAccessor()) {
$(element).append('<td data-bind="text: ' + property + '"></td>');
}
}
};
I've created a jsFiddle to demonstrate it too.
Here is some updated html to get a header and the rows with thead and tbody
<table class="table" >
<thead data-bind="with: page().users()[0]">
<tr data-bind="createHeaderRow: $data">
</tr>
</thead>
<tbody data-bind="foreach: page().users()">
<tr data-bind="createTableRow: $data">
</tr>
</tbody>
</table>

Knockoutjs' foreach not working when single data has returned

I have a table which is shown below. When multiple data comes, it is shown properly but if a single data come, data isn't shown in the table. I suspect absence of brackets in single data..
Multiple Data Sample:
[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]
Single Data sample
{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39}
Table and scripts:
<script type="text/javascript">
$(document).ready(function () {
function ProductViewModel() {
var self = this;
self.productData = ko.observable();
self.productId = ko.observable();
self.getAllProducts = function () {
$.get('/api/products', {}, self.productData);
};
self.getProductById = function () {
$.get('/api/products/' + self.productId(), {}, self.productData);
};
}
ko.applyBindings(new ProductViewModel());
});
</script>
<input id="txtId" type="text" data-bind="value: productId" />
<button id="btnGetSpeProduct" data-bind="click: getProductById">Get Product By Id</button>
<button id="btnGetProducts" data-bind="click: getAllProducts">Get All Products</button><br />
<table data-bind="with: productData">
<thead>
<tr>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
</tr>
</thead>
<tbody data-bind="foreach: $data">
<tr>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: Price">
</td>
</tr>
</tbody>
</table>
The foreach binding can accept either an array or an object specifying various options. In this case, Knockout thinks the object you're giving it is the latter. It will work if you use the object syntax and specify your data using the data option.
<tbody data-bind="foreach: {data: $data}">
Sample: http://jsfiddle.net/mbest/Dta48/
Yes - it has everything to do with the "absence of brackets in single data".
The one with brackets means that it's an array; a list which can can iterate (foreach).
The one without brackets means that it's an object; something which can be stored inside an array, but can not be iterated using foreach.
So, you want it to act like an array so you can iterate over the result. First step, you'll need to use an observableArray instead of observable:
self.productData = ko.observableArray();
Next, you'll need to push the data you $.get to that array, instead of directly binding them.
$.get('/api/products', function(data) {
// Iterate over the data variable, and use
// self.productData.push(ITEM)
// to add it to the array
});
That should do it - good luck!
use observableArray instead of observable
self.productData = ko.observableArray();