Knockout bindings from JSON file issues - javascript

I am using Typescript to define my Knockout ViewModel.
I have a JSON file, the structure of which can be seen here (Github gist as It's a bit large to paste here).
The structure is basically:
OrderLine (the root) -> milestones -> factory_date
Or orally: (many) order lines have (many) milestones, which each have (one) factory date.
I am trying to build a ViewMOdel with the following:
var FactoryAppViewModel = (function () {
function FactoryAppViewModel(seasonID) {
var self = this;
self.seasonID = seasonID;
self.orderlines = ko.observableArray([]);
this.buildViewModel();
}
FactoryAppViewModel.prototype.buildViewModel = function () {
var self = this;
var getOrderLines = HTTP.get("/season/" + self.seasonID + "/orderlines").done(function (data) {
self.orderlines(JSON.parse(data));
}).fail(function () {
error("Could not get orderlines");
});
};
As far as I know, the JSON.parse on the data here will apply the values to the orderlines ko.observableArray([]), However I need to apply a ko.observable to the order lines children (milestones), and to a milestones child (factory_date) as well. And I don't know how to do this. Least of all from JSON.
I have read this but it didn't seem to help me.
I know that the observable isn't applied, because when i change a factory_date in the view, it doesn't update the viewmodel.
Any help would be appreciated. The javascript above is the compiled TypeScript.
EDIT:
Here is an example of the way I'm accessing the code in the view:
<tbody data-bind="foreach: orderlines">
<tr>
<td data-bind="text: factory.name"></td>
<!-- ko foreach: milestones -->
<!-- ko if: factory_date == null -->
<td>
<span>TBA</span>
</td>
<!-- /ko -->
<!-- ko if: factory_date !== null -->
<td>
<div class="wrapper-wrapper">
<div class="btn btn-primary dateChanger">
<span data-bind="text: moment(factory_date.milestone_date).format('DD-MM-YYYY')"></span>
</div>
<div class="date-update-wrapper text-center">
<input type="text" data-bind="attr: {value: moment(factory_date.milestone_date).format('DD-MM-YYYY')}" class="form-control datetimepicker">
<a class="save-date btn btn-success" data-bind="click: function(){$root.saveDate(factory_date, $parent)}"><i class="fa fa-check"></i></a>
<a class="cancel-date btn btn-danger"><i class="fa fa-times"></i></a>
</div>
</div>
</td>
<!-- /ko -->
<!-- /ko -->
</tr>
</tbody>
The part that made me aware I had an issue was this part:
data-bind="click: function(){$root.saveDate(factory_date, $parent)}"
I made a simple saveDate method, which was console.log(factory_date.milestone_date), and it returned the default JSON data, despite me editing it in the view (using the datepicker).

Knockout does not map children in lists to observables by default. There is a plugin called ko.mapping that can help you achieve what you are looking for.
You can set up a "children" mapping, or loop through your children, manually making them observable (In this case from JavaScript):
var mappedChildren = [];
var children = someObj.children();
for (var i = 0; i < children.length; i++) {
var mappedChild = ko.mapping.fromJS(children[i], mappingFunction);
mappedChildren.push(mappedChild);
}
someObj.children(mappedChildren);

Related

Knockout view not removing item from view after delete

I have this code that successfully deletes an exam from a list of exams displayed on a page, but the page still shows the deleted exam. You have to manually refresh the page for the view to update. We are using a simlar pattern on other pages and it's working correctly. I don't understand why it doesn't work on this page.
// Used to handle the click event for Delete
remove = (exam: Models.Exam) => {
$("#loadingScreen").css("display", "block");
var examService = new Services.ExamService();
examService.remove(exam.examId()).then(() => {
examService.getByFid().then((examinations: Array<Models.Exam>) => {
this.exams(examinations);
this.template("mainTemplate");
});
}).fail((error: any) => {
// Add this error to errors
this.errors([error]);
window.scrollTo(0, 0);
}).fin(() => {
$("#loadingScreen").css("display", "none");
});
}
Here's the UI code that displays the list of exams
<div class="section module">
<!-- ko if: exams().length > 0 -->
<!-- ko foreach: exams.sort(function(a,b){return a.mostRecentDateTaken() > b.mostRecentDateTaken() ? 1:-1}) -->
<div class="addremove_section bubbled">
<a class="button open_review" data-bind="click: $root.edit">Edit</a>
<a class="button open_review" data-bind="click: $root.remove">Delete</a>
<div class="titleblock">
<h4 data-bind="text: 'Exam Name: ' + examTypeLookup().examTypeName()"></h4>
<div data-bind="if:examEntityLookup()!=null">
<div data-bind=" text: 'Reporting Entity: ' + examEntityLookup().description()"></div>
</div>
<div data-bind="text: 'Most recent date taken: ' + $root.formatDate(mostRecentDateTaken())"></div>
<div data-bind="text: 'Number of attempts: ' + numberOfAttempts()"></div>
<div data-bind="text: 'Pass/Fail Status: ' + $root.PassFailEnum(passFailId())"></div>
</div>
<div class="clearfix"></div>
</div>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: exams().length == 0 -->
<div class="addremove_section bubbled">
<div class="titleblock">
<div>No Exams Have Been Entered.</div>
</div>
</div>
<!-- /ko -->
</div>
EDIT: I discovered that if I remove the sort from this line in the view
<!-- ko foreach: exams.sort(function(a,b){return a.mostRecentDateTaken() > b.mostRecentDateTaken() ? 1:-1}) -->
to
<!-- ko foreach: exams -->
it works! The only problem is that I need the data sorted.
I removed the sorting from the view and did the sorting in the service. Not really sure why I can't sort in the view. I assume it's a knockout.js bug.
<!-- ko foreach: exams -->
[HttpGet]
[Route("api/exam")]
public IEnumerable<TDto> GetApplicantExams()
{
var dtos = GetCollection(() => _examService.GetApplicantExams(UserContext.Fid).OrderBy(e => e.DateTaken));
return dtos.ForEach(t => AddItems(t));
}
It's not a bug in Knockout. Since the sort invocation (as you're doing it) is not under the control of a computed/dependent observable, there's nothing to trigger it to resort. You've basically broken the connection between the UI (or more technically, the bindingHandler) and the ko.observable which KO uses for tracking changes.
I've run into this many times where I work, and the general pattern I use is something like this:
var viewmodel = {
listOfObjects:ko.observableArray(),
deleteFromList:deleteFromList,
addToList:addToList,
}
//in your HTML, you'll do a foreach: listOfSortedObjects (instead of listOfObjects)
viewmodel.listOfSortedObjects = ko.computed(function(){
//Since this is *inside* the change tracking ecosystem, this sort will be called as you would expect
return viewmodel.listOfObjects().sort(yourSortingFunction);
});
//Since you cannot edit a (normal) computed, you need to do your work on the original array as below.
function deleteFromList(item){
viewmodel.listOfObjects.remove(item);//Changing this array will trigger the sorted computed to update, which will update your UI
}
function addToList(item){
viewmodel.listOfObjects.push(item);
}

ObservableArray not binding to GUI

I'm new with knockout.js and trying to fix data binding on a site that is build on Laravel and is using knockout.js.
Observable array works well and items can be pushed and popped without issues. The problem is with the binding to GUI. When items are pushed to array those are added to GUI, but nothing else works, like removing items, and also when adding more items later on those are added on the top of the GUI element list, not added after existing items on the GUI. The observable array is having correct items after push/pop/removeall, its just not reflecting to GUI.
I guess that the problem is that observable array is not binded to GUI, but I cannot figure out what could be wrong.
Stripped code:
Chat.init = function(){
Chat.viewModel = new Chat.ViewModel;
ko.applyBindings(Chat.viewModel, $('#msg_canvas').get(0));
};
Chat.ViewModel = function(){
self.messages = ko.observableArray();
self.setMessages = function(msgs){
_.each(msgs, function(msg){
self.messages.push(msg);
});
};
self.clearMessages = function(data, e){
self.messages.removeAll();
}
}
clearMessages is called via onclick: data-bind="click: $parent.clearMessages
The HTML is this:
<div id="msg_canvas" class="msg-wrap col-md-12"
style="height:274px;overflow-y:scroll;" data-bind="foreach: messages">
<div class="media msg">
<div class="media-body">
<span data-bind="text: sent_at"></span>
<small class="col-lg-10" data-bind="text: message"></small>
</div>
</div>
Any help or pointer to what could be causing the problem would be highly appreciated.
UPDATE: added inner HTML which was not included to post before
You need to have a control inside the div to hold your messages, like a <span> or <p>. Otherwise, you're simply doing the foreach without outputting the values. So your div should look something like this, using $data to access the value:
<div id="msg_canvas" data-bind="foreach: messages">
<p data-bind="text: $data"></p>
</div>
Here's a working snippet based on your code (setMessages slightly modified / hard coded with values):
ViewModel = function(){
self.messages = ko.observableArray([]);
self.setMessages = function(){
var msgs = ['message','message','message'];
_.each(msgs, function(msg){
self.messages.push(msg + ' ' + self.messages().length);
});
};
self.clearMessages = function(data, e){
self.messages.removeAll();
}
self.removeMessage = function(item){
self.messages.remove(item);
}
};
ko.applyBindings(new ViewModel());
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="msg_canvas" class="msg-wrap col-md-12"
style="height:274px;overflow-y:scroll;border: black solid 1px" data-bind="foreach: messages">
<p data-bind="text: $data"></p>
<input type="button" data-bind="click: removeMessage" value="Remove Item" />
</div>
<input type="button" data-bind="click: setMessages" value="Add Message" />
<input type="button" data-bind="click: clearMessages" value="Remove All" />

How can I apply KnockoutJS on a master page and an individual page?

I'm stuck on an older WebForms project and I'd like to know if there's a recommended approach for my scenario.
Goal
I have a feedback form in a modal dialog that I bound up using KnockoutJS.
I would like the feedback form to be available on all pages, via a link in the footer of the site.
I would like to have several other pages using knockout as well with their own individual scripts & bindings, irrespective of the feedback form bindings in the modal.
I have some pages that do not use knockout at all. I would like them not to have to insert code to accomplish this.
I would like to avoid global variables, if possible, in favor of namespaced JavaScript.
In essence, I would like for the viewmodels on the page and the feedback viewmodel not to be aware of each others' existence.
Current Setup
Our footer links are in a Site.master file, and so that's where I've placed the Feedback.js script and the div for the modal which has the bindings. So on the master page, I call ko.applyBindings(vm, referenceToFeedbackDiv), which works fine to wire up the feedback form.
Our individual pages occasionally have a knockout viewmodel, and so they may call ko.applyBindings(vm), since to their knowledge they'd like to apply the vm to their entire page.
Problem
This causes a conflict in knockout because one vm is being applied to the feedback form via the Site.master call, and one vm is being applied to the entire body by the page after it.
Question
How can I enable these two things -- a modal dialog across all pages that uses knockout, and individual knockout pages -- to work in harmony?
Demonstration of the Issue in (the Current) Code
Remember, the issue is that I want to be able to have one feedback VM that applies only to the feedback div across the client site, and I want to have other VMs able to be applied that aren't required to know anything about the feedback vm.
Master Page file (Site.Master) -- Excerpt
This is on every page:
<div class="page">
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</div>
<div class="footer">
© <%=DateTime.Now.Year.ToString() %> Company, Inc. | Home | About |
<!-- begin feedback area -->
<span id="FeedbackArea">
<a data-bind="click: showModal">Feedback</a>
<div id="feedback-modal" title="What's on your mind?">
<div class="btn-group" id="feedbackButtonGroup">
<button class="btn" data-bind="click: UpdateFeedbackType" style="padding-top: 6px;">
<i class="fa fa-warning fa-2x fa-align-center"></i>
<br />
<span>Problem</span>
</button>
<button class="btn" data-bind="click: UpdateFeedbackType" style="padding-top: 6px;">
<i class="fa fa-question-circle fa-2x fa-align-center"></i>
<br />
<span>Question</span>
</button>
<button class="btn" data-bind="click: UpdateFeedbackType" style="padding-top: 6px;">
<i class="fa fa-lightbulb-o fa-2x fa-align-center"></i>
<br />
<span>Suggestion</span>
</button>
<button class="btn" data-bind="click: UpdateFeedbackType" style="padding-top: 6px;">
<i class="fa fa-thumbs-o-up fa-2x fa-align-center"></i>
<br />
<span>Praise</span>
</button>
<button class="btn" data-bind="click: UpdateFeedbackType" style="padding-top: 6px;">
<i class="fa fa-info-circle fa-2x fa-align-center"></i>
<br />
<span>General</span>
</button>
</div>
<br />
<br />
<textarea rows="5" placeholder="Enter feedback here" data-bind="value: feedbackText, valueUpdate: 'afterkeydown'"></textarea>
<br />
<br />
<button>Send Feedback</button>
<button data-bind="click: CancelFeedback">Cancel</button>
<h3>Other Information: </h3>
<ul>
<li><strong>Feedback Type:</strong> <span data-bind="text: feedbackType"></span></li>
<li><strong>Current URL:</strong> <span data-bind="text: pageUserIsOn"></span></li>
<li><strong>Current User: </strong><%=hdnLoggedInUsername.Value %></li>
<li><strong>Current Client: </strong>[Not yet captured]</li>
<li><strong>Current Tab: </strong>[Not yet captured]</li>
</ul>
</div>
</span>
<!-- End feedback area -->
</div>
Feedback.JS -- This is also included in every page
...a somewhat-namespaced definition of a FeedbackVM:
var FeedbackNamespace = FeedbackNamespace || {};
..the definition of the namespace itself:
FeedbackNamespace = {
ViewModel: function () {
// etc. etc.
}
};
...and the declaration of a VM variable plus wiring it up on document.ready():
var FeedbackVM;
$(document).ready(function () {
FeedbackVM = new FeedbackNamespace.ViewModel();
ko.applyBindings(FeedbackVM, $('#FeedbackArea')[0]);
FeedbackVM.Start();
log('FeedbackVM started');
});
Other Pages without Knockout / JS
Other pages may or may not have any javascript on them at all, let alone knockout. On these pages, the FeedbackVM currently works fine.
Pages with their own Knockout ViewModel
These pages would have their own namespaced JS file with their own document.ready() event, that creates a vm of say invoiceUploaderVM = new InvoiceUploader.ViewModel(), and then calls ko.applyBindings(invoiceUploaderVM).
This is where we run into trouble.
Update: One potential Approach and a little trouble
In the Site.master page, I wrapped my entire footer in a "stopBindings: true" div:
<div data-bind="stopBindings: true">
<div class="footer" id="footerDiv">
<!-- Feedback Viewmodel stuff in here -->
</div>
</div>
I've defined stopBindings as:
ko.bindingHandlers.stopBindings = {
init: function () {
return { controlsDescendantBindings: true };
}
};
My Feedback.js file, loaded on every page as part of a global JS file, has:
var FeedbackNamespace = FeedbackNamespace || {};
FeedbackNamespace = {
// defines viewmodel, etc. etc.
};
var FeedbackVM;
$(document).ready(function () {
FeedbackVM = new FeedbackNamespace.ViewModel();
ko.applyBindings(FeedbackVM, $('#footerDiv')[0]);
FeedbackVM.Start();
log('FeedbackVM started');
});
This approach works perfectly well -- as long as there are no other viewmodels being bound. On the pages that inherit from my master page, I might have something like:
$(document).ready(function () {
'use strict';
vm = new invoiceUploader.ViewModel();
ko.applyBindings(vm);
});
I would expect that this:
Sets up the feedback viewmodel applied to the div, stopping other viewmodels
Sets up the invoiceUploader viewmodel and applies it to the body (which is then stopped by the stopBindings div)
However, instead I get an error upon loading the child page along the lines of:
Commenting the line to apply the feedback bindings makes this work just fine again.
What am I doing wrong?
I think I would put the view model for your modal in a global object and do whatever you need to do with it aside from applying the bindings in a shared script:
window.feedbackModal = {
foo: ko.observable("Whatever you need to do here"),
bar: ko.observable("assuming it can be done the same on every page")
};
Then in the Site.master
<div class="feedback-modal" data-bind="with: feedbackModal">
<p data-bind="text: foo"></p>
<p data-bind="text: bar"></p>
</div>
And in every individual page's script:
function ViewModel() {
this.individualProperty = ko.observable(true);
this.specificAction = function() { /* do something specific to this page */ };
this.feedbackModal = window.feedbackModal;
}
ko.applyBindings(new ViewModel());
So window.feedbackModal could be undefined and it won't cause you problems, but if you ko.applyBindings, you have to have a feedbackModal property exposed in the view model or you'll get errors applying those bindings.
Of course, there are more clever ways you could implement this basic idea in order to fit your patterns the best, but the big point is, as you know, you can't apply bindings twice, so you need to defer that task to your most specific code and expose your reusable code to to it.
Here is another strategy for separation of common modules from page dependant modules:
// An example of a module that runs on everypage
var modalDialog = function(){
this.name = "dialog1";
this.title = ko.observable("My Modal Title");
this.content = ko.observable("My Modal content is also something");
}
// An example of a module that runs on everypage
var modalDialog2 = function(){
this.name = "dialog2";
this.title = ko.observable("My Modal Title 2");
this.content = ko.observable("My Modal content is also something 2");
}
// Either generate it automatically or by hand
// to represent which modules are common
var commonModules = [modalDialog, modalDialog2];
// An example of a module only for this page
var pageModule = function(){
this.pageFunction = function(){
alert("Called page function");
}
}
// Composition is the final object you will actually bind to the page
var composition = {
pageMod: new pageModule()
}
// Let's add the common modules to the composition
ko.utils.arrayForEach(commonModules, function(item){
var module = new item();
composition[module.name] = module;
});
// Bind the composition
ko.applyBindings(composition);
example HTML for this would be:
<div class="modalDialog">
<h2 data-bind="text: dialog1.title"><h2>
<h2 data-bind="text: dialog1.content"><h2>
</div>
<div class="modalDialog">
<h2 data-bind="text: dialog2.title"><h2>
<h2 data-bind="text: dialog2.content"><h2>
</div>
<div id="content">
<h2>Welcome to page</h2>
<div id="somePageStuff">
Click me
</div>
</div>
Link to the jsfille for this
You can set this up by using a technique to not have scope your bindings to a specific area in your page.
Check out: How to stop knockout.js bindings evaluating on child elements
Example:
http://jsfiddle.net/anAgent/RfM2R/
HTML
<div id="Main">
<label data-bind="text: ViewModel.Name">default</label>
<div data-bind="stopBindings: true">
<div id="ChildBinding">
<label data-bind="text: AnotherViewModel.Name">default</label>
</div>
</div>
</div>
JavaScript
$(function () {
ko.bindingHandlers.stopBindings = {
init: function () {
return {
controlsDescendantBindings: true
};
}
};
var data = {
ViewModel: {
Name: "Testing"
}
};
var data2 = {
AnotherViewModel: {
Name: "More Testing"
}
};
ko.applyBindings(data, $("#Main")[0]);
ko.applyBindings(data2, $("#MyModalHtml")[0]);
});

How to remove items from external observableArray with KnockoutJS

The goal
Remove items from external observableArray using KnockoutJS.
The problem
There is two observableArray in my application. One for available products to buy and other to products that I have added in the Summary by clicking in add button.
Until here, all works fine. But now I need to remove items from Summary and change the button state/style — and I do not know how to access an external observableArray to do this.
To understand my problem, check out this jsFiddle or see the markup in the next topic.
As you could see, when I click on add button, the product goes to Summary. When I click on remove — regardless if the button is from the summary or the product — I want to change the button state and remove the item from summary. Technically speaking, I want to remove the item from items' observableArray utilizing the products' observableArray.
My code
HTML:
<ul class="summary">
<!-- ko foreach: Summary.items -->
<p data-bind="text: name"></p>
<button class="btn btn-danger btn-mini remove-item">
<i class="icon-remove">×</i>
</button>
<!-- /ko -->
</ul>
<h1>What would you to buy?</h1>
<ul class="products">
<!-- ko foreach: Product.products -->
<li>
<h3 data-bind="text: name"></h3>
<p data-bind="text: desc"></p>
<!-- ko if:isAdded -->
<button data-bind="if: isAdded" class="btn btn-small btn-success action remove">
<i data-bind="click: $root.Summary.remove" class="icon-ok">Remove</i>
</button>
<!-- /ko -->
<!-- ko ifnot:isAdded -->
<form data-bind="submit: function() { $root.Summary.add($data); }">
<button data-bind="ifnot: isAdded" class="btn btn-small action add">
<i class="icon-plus">Add</i>
</button>
</form>
<!-- /ko -->
</li>
<!-- /ko -->
</ul>
JavaScript:
function Product(id, name, desc) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
self.desc = ko.observable(desc);
self.isAdded = ko.observable(false);
}
function Item(id, name) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
}
function SummaryViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.add = function (item) {
self.items.push(new Item(item.id(), item.name()));
console.log(item);
item.isAdded(true);
};
self.remove = function (item) {
item.isAdded(false);
};
};
function ProductViewModel(products) {
var self = this;
self.products = ko.observableArray(products);
};
var products = [
new Product(1, "GTA V", "by Rockstar"),
new Product(2, "Watch_Dogs", "by Ubisoft")
];
ViewModel = {
Summary: new SummaryViewModel(),
Product: new ProductViewModel(products)
}
ko.applyBindings(ViewModel);
You can search for it.
You can query the cart for an item with the same id, and remove it
self.remove = function (item) {
var inItems = self.items().filter(function(elem){
return elem.id() === item.id(); // find the item with the same id
})[0];
self.items.remove(inItems);
item.isAdded(false);
};
Unless you have hundreds of thousands of items, that should be perfectly fast enough. Just remember to use items.remove() so it'll know to update the observableArray :)
Once you've declared products as an observableArray, you should just be able to call remove on it (according to this). Given you have a reference to the object being deleted to pass in.

Render container conditionally

Is it possible to render container for a template based on condition with knockout.js?
This does not work, but shows what i want to do:
<div data-bind="foreach: items">
<!-- ko if: $data.startContainer -->
<div class="container">
<!-- ko -->
<div data-bind="html: $data.contentElement"></div>
<!-- ko if: $data.endContainer -->
</div>
<!-- ko -->
</div>
Found a thread on knockout.js github site that indicates this as not possible with the native templating model:
https://github.com/SteveSanderson/knockout/issues/307
Apparently, the closing comment is understand as internal to the not closed div tag.
My hopes were on the dynamic templates, but failed also like shown in the fiddle.
http://jsfiddle.net/XbdGs/3/
<script type="text/html" id="withContainer">
<div class="container">
<!-- ko template: 'withoutContainer' -->
<!-- /ko -->
</div>
</script>
From that i conclude you can try the 3 foreachs solution, use Posthuma suggestion or fallback to another templating engine like jquery.tmpl or Underscore as mentioned on knockout documentation.
http://knockoutjs.com/documentation/template-binding.html
You can do this through a custom binding.
Update:
If you want to open a div and close from another item, the custom binding would look like this:
ko.bindingHandlers.myCustomBinding = {
update: function(element, valueAccessor, allBindings, data, context){
var value = valueAccessor();
var items = ko.utils.unwrapObservable(value);
var currentElement = element;
ko.utils.arrayForEach(items, function(item){
if(item.startContainer){
var container = document.createElement('div');
$(container).append(item.displayContent);
$(container).addClass("container");
currentElement = container;
}
else if(item.endContainer){
$(currentElement).append(item.displayContent);
$(element).append(currentElement);
currentElement = element;
}
else{
$(currentElement).append(item.displayContent);
}
});
}
};
HTML:
<div data-bind='myCustomBinding: items'></div>
There are probably better ways to write this code and possibly use knockouts built-in bindings, but this should be enough to get you started.
http://jsfiddle.net/posthuma/f5wG4/2

Categories

Resources