KnockoutJS - show accumulate value for each item - javascript

How can I display in a table the accumulate value for each item in a observableArray with KnockoutJS?
I need somethin like:
function ViewModel(){
var self = this;
self.Item = function(day,note){
this.day = ko.observable(day);
this.note = ko.observable(note);
};
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
var vm = new ViewModel();
var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) {
return new vm.Item(item.day, item.note);
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>Day</th><th>Note</th><th>Accumulate</th></tr>
</thead>
<tbody data-bind="foreach: arrItems">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td >the currente 'note' + the anterior 'note'</td>
</tr>
</tbody>
</table>
The last column should display the sum of current item + anterior item.
Thanks.

I'm not exactly sure what value you want the third column to be, but the main approach remains the same:
Give your Item class access to their "sibling items" by passing a reference to the array
In a computed property, do a "look behind" by looking up the items own index.
Perform some sort of calculation between two (or more) Item instances and return the value
For example, this acc property returns the acc of the previous Item and ones own note property:
var Item = function(day, note, siblings){
this.day = ko.observable(day);
this.note = ko.observable(note);
this.acc = ko.pureComputed(function() {
var allItems = siblings();
var myIndex = allItems.indexOf(this);
var base = myIndex > 0
? allItems[myIndex - 1].acc()
: 0
return base + this.note();
}, this);
};
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.items(itemsFromServer.map(function(item) {
return new Item(item.day, item.note, self.items);
})
);
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>Day</th>
<th>Note</th>
<th>Accumulate</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td data-bind="text: acc"></td>
</tr>
</tbody>
</table>

Related

Set href using $root value within foreach loop

The link in the first td column spazzes out when trying to bind to $root.rootBaseUrl.
In the second td column, the same rootBaseUrl observable prints perfectly.
The difference is that in the first td column, I am trying to set the value within attr:.
Also, please note that there is a foreach loop happening at the tbody level. Hence the use of $root prefix.
<tbody data-bind="foreach: siteList">
<tr>
<td><h3><a data-bind="text: SiteName, attr: {href: $root.rootBaseUrl + SiteID}"></a></h3></td>
<td><h3><span data-bind="text: $root.rootBaseUrl"></span></h3></td>
</tr>
</tbody>
var rootBaseUrl = ko.observable("");
var index = window.location.toString().indexOf("RiskOrder");
var baseURL = window.location.toString().substring(0, index);
this.rootBaseUrl(baseURL);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Basically, I am getting the current browser URL in the JS, stripping it to the base root url, then trying to add this static URL to the href binding and concatenating with a dynamic SiteID value.
Is this possible?
Replace attr with text and get a glimplse of your problem:
function Vm(){
var self = this;
self.SiteID = ko.observable("AX123");
}
function RootVm(){
var self = this;
var index = window.location.toString().indexOf("RiskOrder");
var baseURL = window.location.toString().substring(0, index);
self.rootBaseUrl = ko.observable("");
self.SiteName = ko.observable("My Site");
self.rootBaseUrl(baseURL);
self.SiteList = ko.observableArray([new Vm()]);
}
ko.applyBindings(new RootVm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tbody data-bind="foreach: SiteList">
<tr>
<td>
<h3><a data-bind="text: $root.rootBaseUrl + SiteID"></a></h3>
</td>
<td>
<h3><span data-bind="text: $root.rootBaseUrl"></span></h3>
</td>
</tr>
</tbody>
</table>
It renders function....., so a textual representation of a function. This is because rootBaseUrl is a function. If you want to use it in an expression, you have to use parentheses:
<h3><a data-bind="text: $root.rootBaseUrl()+ SiteID()"></a></h3>
If you use it as the only thing in a binding, the parentheses are optional:
<h3><span data-bind="text: $root.rootBaseUrl()"></span></h3>
So your fix would be:
function Vm(){
var self = this;
self.SiteID = ko.observable("AX123");
self.SiteName = ko.observable("My Site");
}
function RootVm(){
var self = this;
var index = window.location.toString().indexOf("RiskOrder");
var baseURL = window.location.toString().substring(0, index);
// On SO Snippets window.location works differently so we hack it:
baseURL = "https://example.com/my-website/url/";
self.rootBaseUrl = ko.observable("");
self.rootBaseUrl(baseURL);
self.SiteList = ko.observableArray([new Vm()]);
}
ko.applyBindings(new RootVm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tbody data-bind="foreach: SiteList">
<tr>
<td>
<h3><a data-bind="text: SiteName, attr: { href: $root.rootBaseUrl() + SiteID() }"></a></h3>
</td>
<td>
Second column
</td>
</tr>
</tbody>
</table>
Or use a computed so you can (a) unit test the logic and (b) make the parentheses optional again:
function Vm(urlBaseVm){
var self = this;
self.SiteID = ko.observable("AX123");
self.SiteName = ko.observable("My Site");
self.hrf = ko.computed(function() {
return urlBaseVm.rootBaseUrl() + self.SiteID();
});
}
function RootVm(){
var self = this;
var index = window.location.toString().indexOf("RiskOrder");
var baseURL = window.location.toString().substring(0, index);
// On SO Snippets window.location works differently so we hack it:
baseURL = "https://example.com/my-website/url/";
self.rootBaseUrl = ko.observable("");
self.rootBaseUrl(baseURL);
self.SiteList = ko.observableArray([new Vm(self)]);
}
ko.applyBindings(new RootVm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<tbody data-bind="foreach: SiteList">
<tr>
<td>
<h3><a data-bind="text: SiteName, attr: { href: hrf }"></a></h3>
</td>
<td>
Second column
</td>
</tr>
</tbody>
</table>

Knockout does not update UI when observableArray is a property of other model

I have 2 observableArray connected to each other. When a "feature" is clicked, I try to show "tasks" of it. However KO, does not update UI when I clicked a feature. On the console, I can track my viewModel, and I can see tasks successfully loaded on selectedFeature. However, UI does not update, even all arrays are defined as observable.
Here is a live demo on fiddle.
Please tell me where I am missing?
function GetFeatures() {
var url = "/Project/GetFeatures";
$.get(url, "", function (data) {
$.each(JSON.parse(data), function (i, item) {
projectVM.features.push(new featureViewModelCreator(item, projectVM.selectedFeature));
});
});
};
function GetTasks(selectedFeature) {
var url = "/Task/GetTaskList";
$.get(url, { "FeatureId": selectedFeature.FeatureId }, function (data) {
$.each(JSON.parse(data), function (i, item) {
selectedFeature.tasks.push(new taskViewModelCreator(item, selectedFeature.selectedTask));
});
});
};
function taskViewModelCreator(data, selected) {
var self = this;
self.TaskId = data.TaskId;
self.Title = data.Name;
self.Status = data.Status.Name;
self.CreatedDate = data.CreatedDate;
self.UserCreatedFullName = data.UserCreated.FullName;
this.IsSelected = ko.computed(function () {
return selected() === self;
});
}
function featureViewModelCreator(data, selected) {
var self = this;
self.FeatureId = data.FeatureId;
self.Name = data.Name;
self.Status = data.Status.Name;
self.CreatedDate = data.CreatedDate;
self.UserCreatedFullName = data.UserCreated.FullName;
self.tasks = ko.observableArray();
this.IsSelected = ko.computed(function () {
return selected() === self;
});
self.selectedTask = ko.observable();
self.taskClicked = function (clickedTask) {
var selection = ko.utils.arrayFilter(self.model.tasks(), function (item) {
return clickedTask === item;
})[0];
self.selectedTask(selection);
}
}
function projectViewModelCreator() {
var self = this;
self.ProjectId = 1;
self.features = ko.observableArray();
self.selectedFeature = ko.observable();
self.featureClicked = function (clickedFeature) {
self.selectedFeature(clickedFeature);
GetTasks(clickedFeature);
}
}
var projectVM = new projectViewModelCreator();
ko.applyBindings(projectVM, $('.taskmanTable')[0]);
GetFeatures();
On the UI
<div class="taskmanTable">
<table class="table table-hover featureList">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody data-bind="foreach: features">
<tr data-bind="click: $root.featureClicked, css: { active : IsSelected } ">
<td><span data-bind="text: Name"> </span></td>
</tr>
</tbody>
</table>
<table class="table table-hover taskList">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody data-bind="foreach: selectedFeature.tasks">
<tr>
<td><span data-bind="text:Title"></span></td>
</tr>
</tbody>
</table>
</div>
Here is the correct version with key notes: here. KO documentation is quite a detailed one.
You have mentioned an interesting note about UI code style: "As I know, we don't use () on UI". I did not put attention to this fact before.
We can really omit brackets for an observable: ko observable;
View contains an observable with no brackets:
<label>
<input type="checkbox" data-bind="checked: displayMessage" /> Display message
</label>
Source code:
ko.applyBindings({
displayMessage: ko.observable(false)
});
We can omit brackets for an observable array on UI: ko observable array
View contains: <ul data-bind="foreach: people">, while
View model has:
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
We can omit brackets on UI for 'leaf' observables or observables arrays. Here is your modified code sample. data-bind="if: selectedFeature" and data-bind="foreach: selectedFeature().tasks"> only leaf observable braces are omitted.
Finally, can we omit brackets for 'parent' observables? We can do it by adding another ko UI-statement (with instead of if, example 2).
The with binding will dynamically add or remove descendant elements
depending on whether the associated value is null/undefined or not
But, I believe, we can not omit brackets for parent nodes outside UI statement, because it is equal to a javascript statement: projectVM.selectedfeature().tasks. Othervise projectVM.selectedfeature.tasks will not work, because observables does not have such property tasks. Instead an observable contains an object with that property, which is retrieved by calling it via brackets (). There is, actually, an example on knockoutjs introduction page. <button data-bind="enable: myItems().length < 5">Add</button>
The code below uses the following fact (which can be found here, example 2):
It’s important to understand that the if binding really is vital to
make this code work properly. Without it, there would be an error when
trying to evaluate capital.cityName in the context of “Mercury” where
capital is null. In JavaScript, you’re not allowed to evaluate
subproperties of null or undefined values.
function GetFeatures() {
var data = {
Name: "Test Feature",
FeatureId: 1
}
projectVM.features.push(new featureViewModelCreator(data, projectVM.selectedFeature));
};
function GetTasks(selectedFeature) {
var data = {
Title: "Test Feature",
TaskId: 1
}
selectedFeature().tasks.push(new taskViewModelCreator(data, selectedFeature().selectedTask));
};
function taskViewModelCreator(data, selected) {
var self = this;
self.TaskId = data.TaskId;
self.Title = data.Title;
// Step 3: you can omit $root declaration, I have removed it
// just to show that the example will work without $root as well.
// But you can define the root prefix explicitly (declaring explicit
// scope may help you when you models become more complicated).
// Step 4: data-bind="if: selectedFeature() statement was added
// to hide the table when it is not defined, this statement also
// helps us to avoid 'undefined' error.
// Step 5: if the object is defined, we should referense
// the observable array via -> () as well. This is the KnockoutJS
// style we have to make several bugs of that kind in order
// to use such syntax automatically.
this.IsSelected = ko.computed(function() {
return selected() === self;
});
}
function featureViewModelCreator(data, selected) {
var self = this;
self.FeatureId = data.FeatureId;
self.Name = data.Name;
self.tasks = ko.observableArray();
this.IsSelected = ko.computed(function() {
return selected() === self;
});
self.selectedTask = ko.observable();
}
function projectViewModelCreator() {
var self = this;
self.ProjectId = 1;
self.features = ko.observableArray();
self.selectedFeature = ko.observable();
self.featureClicked = function(clickedFeature) {
self.selectedFeature(clickedFeature);
GetTasks(self.selectedFeature);
}
}
var projectVM = new projectViewModelCreator();
ko.applyBindings(projectVM, $('.taskmanTable')[0]);
GetFeatures();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="taskmanTable">
<table class="table table-hover featureList">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody data-bind="foreach: features">
<tr data-bind="click: $root.featureClicked, css: { active : IsSelected } ">
<td><span data-bind="text: Name"> </span></td>
</tr>
</tbody>
</table>
<hr/>
<table data-bind="if: selectedFeature()" class="table table-hover taskList">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody data-bind="foreach: selectedFeature().tasks()"><!-- $root -->
<tr>
<td><span data-bind="text: Title"></span></td>
</tr>
</tbody>
</table>
</div>

How can I get element's data to Array with jQuery?

Here is a table:
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
I want to get every tr's data-id,
I know how to get it with $.each,
I know this can do it:
var trArray = [];
$.each($('table tr'), function () {
trArray.push($(this).data('id'));
})
and $('table tr').data('id') only can get the first tr's data-id
But is there anyway easy and graceful to do this?
In one sentence to get data-id's array [1,2,3,4,5,6] with jQuery or js?
Try using $.map()
var data = $.map($("table tr"), function(el) {return $(el).data().id})
This is another option, which uses pure js.
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){
return e.dataset.id;
});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
You could 'simplifly' like this if you want
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
Here's the jQuery option:
var ids = $.map($("tr"),function(e){return e.dataset.id});
var getIds = function() {
var ids = $.map($("tr"),function(e){return e.dataset.id});
alert(ids);
};
document.addEventListener("DOMContentLoaded", getIds);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>

KnockoutJS - how to remove an object from an observableArray when remove is not a function?

I have a structure of an array with a nested array. I am trying to remove an item from the nested array but I get the error that "remove is not a function".
I've recreated the problem in a simple jsFiddle - http://jsfiddle.net/rswailes/gts5g/ and also pasted the code below.
It's possible that the way I have set up the observables is not correct, but I'm stumped.
This is my html:
<script id="bookGroupTemplate" type="text/html">
<br/>
<h3><span data-bind="text: group_name"></span></h3>
<table>
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Genre</th>
<th></th>
</tr>
</thead>
<tbody data-bind='template: {name: "bookRowTemplate", foreach: books}'></tbody>
</table>
</script>
<script id="bookRowTemplate" type="text/html">
<tr>
<td data-bind="text: author"></td>
<td data-bind="text: title"></td>
<td data-bind="text: genre"></td>
</tr>
</script>
<h1>Books!</h1>
<div data-bind='template: {name: "bookGroupTemplate", foreach: bookGroups}'></div>
<br/><br/>
<button data-bind="click: function(){viewModel.handleButtonClick(); }">Move One From Now to Later</button>
This is the javascript:
var BookGroup = function(group_name, booksToAdd){
var self = this;
this.group_name = ko.observable(group_name);
this.books = ko.observableArray();
_.each(booksToAdd, function(book){
self.books.push(ko.observable(book));
});
}
var Book = function(author, title, genre) {
this.author = ko.observable(author);
this.title = ko.observable(title);
this.genre = ko.observable(genre);
}
var PageViewModel = function() {
var self = this;
this.bookGroups = ko.observableArray();
this.bookToUse = new Book("Robin Hobb", "Golden Fool", "Fantasy");
this.indexAction = function() {
var groups = [];
var booksArray = [];
booksArray.push(this.bookToUse);
booksArray.push(new Book("Patrick R Something", "Name Of The Wind", "Fantasy"));
booksArray.push(new Book("Someone Else", "Game Of Thrones", "Fantasy"));
groups.push(new BookGroup("To Read Now", booksArray));
booksArray = [];
booksArray.push(new Book("Terry Pratchett", "Color of Magic", "Discworld"));
booksArray.push(new Book("Terry Pratchett", "Mort", "Discworld"));
booksArray.push(new Book("Terry Pratchett", "Small Gods", "Discworld"));
groups.push(new BookGroup("To Read Later", booksArray));
this.bookGroups(groups);
};
this.handleButtonClick = function(){
console.log(this.bookGroups()[0].books().length);
this.bookGroups()[0].books().remove(this.bookToUse);
};
};
viewModel = new PageViewModel();
ko.applyBindings(viewModel);
viewModel.indexAction();
Why is remove not recognized here? Is this the right way to construct the model?
Many thanks for any advice :)
There were 2 errors:
You tried to call remove function form javascript array instead observable array.
You don't need to wrap book object with observable when put it to observableArray.
Have you tried remove on the observableArray and not on its contents, in other words :
this.handleButtonClick = function(){
console.log(this.bookGroups()[0].books().length);
this.bookGroups()[0].books.remove(this.bookToUse);
};
see Observable Arrays

No value is coming in my partial view throught knockout js

var baseUri = '#ViewBag.ApiUrl';
var viewmodel = function () {
var self = this;
self.VoucherDetails = ko.observableArray([]);
$.getJSON(baseUri, this.VoucherDetails);
alert(self.VoucherDetails);
};
<table>
<tbody data-bind='foreach: VoucherDetails'>
<tr>
<td data-bind="text : $data.empcode">
<span data-bind=" text : $data.empcode"></span> test
</td>
<td data-bind=" text : empcode">
<span data-bind=" text : empcode"></span>
</td>
</tr>
</tbody>
</table>
This is my partial view and there is no value coming in empcode or $data.empcode, I am new to knockoutjs. What is wrong in my code?
Your code looks incomplete:
$.getJson never sets the value of VoucherDetails (no callback is passed).
You never call ko.applyBindings
It should be:
var baseUri = '#ViewBag.ApiUrl';
var viewmodel = function () {
var self = this;
self.VoucherDetails = ko.observableArray([]);
$.getJSON(baseUri, function(data){
//create your VoucherDetails here based on the data (push each item to VoucherDetails using $.each
});
};
ko.applyBindings(viewModel);
http://knockoutjs.com/documentation/observableArrays.html

Categories