Knockout.js + ES6 + Underscore Templating - javascript

I am trying to get my head around using Knockout.js to create a product cart. Each item outputs a plus and minus button as well as a remove button. My aim is to be able to have the plus and minus increment or decrement the quantity, and the remove button to remove the product. My constraints are that I can't use JQuery.
I've attempted to separate my app concerns so that I have ShopView, ShopModel and ShopItem (ShopItem is the individual item that is pushed to an observable array within the ShopModel). The buttons are rendered, however when clicking on an individual remove/add/minus button and logging the value of this to the console I only am able to see my JS class, not the individual element to remove or alter. Any insight would be greatly appreciated. I've included the bare-bones snippets of the key parts:
index.html
<script type="text/html" id="itemsList">
{{ _.each(items(), function(item) { }}
<a href="#" data-bind="click: minus" class='left-minus'>–</a>
<p class="qty" data-bind="text: item.quantity"></p>
Remove
<a href="#" data-bind="click: plus" class='right-plus'>&plus;</a>
{{ }) }}
</script>
<section data-bind="template: { name: 'itemsList' }" class="items-inner"></section>`
shopView.js
class shopView {
constructor() {
this.setupShop()
}
setupShop(){
this.model.items.push(new Item(97, 'cover-3', '/media/img/cover-3.jpg', 'Issue 5', 'Spring Summer 17', 1, 10));
ko.applyBindings(this.model);
}
}
module.exports = shopView
shopView.js
let ko = require('knockout');
class shopItem{
constructor (id, url, thumbnail, title, edition, quantity, price) {
this.id = ko.observable(id)(),
this.thumbnail = ko.observable(url)(),
this.title = ko.observable(title)(),
this.edition = ko.observable(edition)(),
this.quantity = ko.observable(quantity)(),
this.price = ko.observable(price)();
this.add = function(){
};
this.minus = function(){
};
}
}
module.exports = shopItem;
shopModel
Shop Item
class shopModel {
constructor() {
this.items = ko.observableArray([]);
this.minus = function(item){
console.log(item);
};
this.plus = function(){
};
this.remove = (item) => {
this.items.remove(item);
};
}
}
module.exports = shopModel;

The click binding provides the current $data value to the callback function. But because you are using Underscore for the loop, $data isn't the item. You can change your click binding to something like this:
<a href="#" data-bind="click: function() {minus(item)}" class='left-minus'>–</a>

Related

Mapping a nested object as an observable from a complex JSON using the create callback

I've got a complex object in a JSON format. I'm using Knockout Mapping, customizing the create callback, and trying to make sure that every object that should be an observable - would actually be mapped as such.
The following code is an example of what I've got:
It enables the user to add cartItems, save them (as a JSON), empty the cart, and then load the saved items.
The loading part fails: It doesn't display the loaded option (i.e., the loaded cartItemName). I guess it's related to some mismatch between the objects in the options list and the object bounded as the cartItemName (see this post), but I can't figure it out.
Code (fiddle):
var cartItemsAsJson = "";
var handlerVM = function () {
var self = this;
self.cartItems = ko.observableArray([]);
self.availableProducts = ko.observableArray([]);
self.language = ko.observable();
self.init = function () {
self.initProducts();
self.language("english");
}
self.initProducts = function () {
self.availableProducts.push(
new productVM("Shelf", ['White', 'Brown']),
new productVM("Door", ['Green', 'Blue', 'Pink']),
new productVM("Window", ['Red', 'Orange'])
);
}
self.getProducts = function () {
return self.availableProducts;
}
self.getProductName = function (product) {
if (product) {
return self.language() == "english" ?
product.productName().english : product.productName().french;
}
}
self.getProductValue = function (selectedProduct) {
// if not caption
if (selectedProduct) {
var matched = ko.utils.arrayFirst(self.availableProducts(), function (product) {
return product.productName().english == selectedProduct.productName().english;
});
return matched;
}
}
self.getProductColours = function (selectedProduct) {
selectedProduct = selectedProduct();
if (selectedProduct) {
return selectedProduct.availableColours();
}
}
self.addCartItem = function () {
self.cartItems.push(new cartItemVM());
}
self.emptyCart = function () {
self.cartItems([]);
}
self.saveCart = function () {
cartItemsAsJson = ko.toJSON(self.cartItems);
console.log(cartItemsAsJson);
}
self.loadCart = function () {
var loadedCartItems = ko.mapping.fromJSON(cartItemsAsJson, {
create: function(options) {
return new cartItemVM(options.data);
}
});
self.cartItems(loadedCartItems());
}
}
var productVM = function (name, availableColours, data) {
var self = this;
self.productName = ko.observable({ english: name, french: name + "eux" });
self.availableColours = ko.observableArray(availableColours);
}
var cartItemVM = function (data) {
var self = this;
self.cartItemName = data ?
ko.observable(ko.mapping.fromJS(data.cartItemName)) :
ko.observable();
self.cartItemColour = data ?
ko.observable(data.cartItemColour) :
ko.observable();
}
var handler = new handlerVM();
handler.init();
ko.applyBindings(handler);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://rawgit.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.js
"></script>
<div>
<div data-bind="foreach: cartItems">
<div>
<select data-bind="options: $parent.getProducts(),
optionsText: function (item) { return $parent.getProductName(item); },
optionsValue: function (item) { return $parent.getProductValue(item); },
optionsCaption: 'Choose a product',
value: cartItemName"
>
</select>
</div>
<div>
<select data-bind="options: $parent.getProductColours(cartItemName),
optionsText: $data,
optionsCaption: 'Choose a colour',
value: cartItemColour,
visible: cartItemName() != undefined"
>
</select>
</div>
</div>
<div>
<button data-bind="text: 'add cart item', click: addCartItem" />
<button data-bind="text: 'empty cart', click: emptyCart" />
<button data-bind="text: 'save cart', click: saveCart" />
<button data-bind="text: 'load cart', click: loadCart" />
</div>
</div>
What needs to be changed to fix it?
P.S.: I've got another piece of code (see it here) that demonstrates a persistance of the selected value even after changing the options - though there optionsValue is a simple string, while here it's an object.
EDIT:
I figured out the problem: the call ko.mapping.fromJS(data.cartItemName) creates a new productVM object, which is not one of the objects inside availableProducts array. As a result, none of the options corresponds to the productVM contained in the loaded cartItemName, so Knockout thereby clears the value altogether and passes undefined.
But the question remains: how can this be fixed?
In the transition from ViewModel -> plain object -> ViewModel you loose the relation between the products in your cart and the ones in your handlerVM.
A common solution is to, when loading a plain object, manually search for the existing viewmodels and reference those instead. I.e.:
We create a new cartItemVM from the plain object
Inside its cartItemName, there's an object that does not exist in handlerVM.
We look in handlerVM for a product that resembles this object, and replace the object by the one we find.
In code, inside loadCart, before setting the new viewmodels:
loadedCartItems().forEach(
ci => {
// Find out which product we have:
const newProduct = ci.cartItemName().productName;
const linkedProduct = self.availableProducts()
.find(p => p.productName().english === newProduct.english());
// Replace the newProduct by the one that is in `handlerVM`
ci.cartItemName(linkedProduct)
}
)
Fiddle: https://jsfiddle.net/7z6010jz/
As you can see, the equality comparison is kind of ugly. We look for the english product name and use it to determine the match. You can also see there's a difference in what is observable and what isn't.
My advice would be to use unique id properties for your product, and start using those. You can create a simpler optionsValue binding and matching new and old values happens automatically. If you like, I can show you an example of this refactor as well. Let me know if that'd help.

Push to observable array with concrete object or not?

How is this:
var Tag = function (data) {
this.name = ko.observable(data.name);
}
//////
self.tags.push(new Tag({name: self.newTagName()}));
different from just this:
self.tags.push({name: self.newTagName()});
I picked up the first form a tutorial and I start learning knockout, but it confused me, and I have tracked down the logic to the second option.
What are the pros for the first one?
Well Both are same when coming to the pushing part but there is a big difference between both as you are pushing a observable in Case-1 were as in other case you trying to assign a value to name .
Performance perspective i don't think it makes a difference . Case-1 is readable and maintainable .
View :
Type 1: Not a observable (Two way binding doesn't exist)
<div data-bind="foreach:tags1">
<input type="text" data-bind="value:name" />
</div>
Type 2: Observable ( Two way binding )
<div data-bind="foreach:tags2">
<input type="text" data-bind="value:name" />
</div>
ViewModel:
var vm = function(){
var self=this;
self.tags1=ko.observableArray();
self.newTagName=ko.observable('Hi there');
self.tags1.push({name: self.newTagName()}); //you just pushing plane text
var Tag = function (data) {
this.name = ko.observable(data.name);
}
self.tags2=ko.observableArray();
self.tags2.push(new Tag({name: self.newTagName()}));
}
ko.applyBindings(new vm());
Working fiddle here
Quick fix to make first case to work do something like this self.tags1.push({name: ko.observable(self.newTagName())})
Basically you would use observables only when the state of the viewmodel property is dynamic, and changes in response to user 'input' (events). For example, if you had a list toolbar with up, down, add and remove buttons, you could have the following JS in your viewmodel:
this.toolbar = [
{name: 'add', action: this.add, icon: 'plus'},
{name: 'remove', action: this.remove, icon: 'close'},
{name: 'up', action: this.moveUp, icon: 'arrow-up'},
{name: 'down', action: this.moveUp, icon: 'arrow-down'}
];
And the following HTML:
<span data-bind="foreach: toolbar">
<button type="button" data-bind="attr: { title: name }, click: action">
<i data-bind="attr: { class: 'fa fa-' + icon}"></i>
</button>
</span>
IE the previous UI requires only one-way binding (model=>view); the buttons will not change.
However, suppose we would add a button to open/ close the details of each list item. This button has a state: open or closed. For this purpose we need to add an observable which holds a boolean in the button object. We also want to change the icon from + to -, and vice-versa on open/close, so 'icon' will be a computed property here, like so:
var toggleButton = {name: 'toggle'};
toggleButton.state = ko.observable(false); // closed by default
toggleButton.action = function() { toggleButton.state(!toggleButton.state()); };
toggleButton.icon = ko.computed(function() {
return toggleButton.state() ? 'minus' : 'plus';});
this.toolbar.push(toggleButton);
And the modified HTML:
<span data-bind="foreach: toolbar">
<button type="button" data-bind="attr: { title: name }, click: action">
<i data-bind="attr: { class: 'fa fa-' + ko.unwrap(icon) }"></i>
</button>
</span>
As for the "what are the pros of regular objects/properties": they are static, so you would use them eg, for a unique "ID" property which never changes after creation. Performance-wise I have had some trouble only when an observable array contains many many items with many many observable properties.
Using constructor functions is handy (vs object literals) when your objects need their own scope, or if you have many of them to share prototype methods, or even, to automate JSON data mapping.
var app = function() {
this.add = this.remove = this.moveUp = this.moveDown = function dummy() { return; };
this.toolbar = [
{name: 'add', action: this.add, icon: 'plus'},
{name: 'remove', action: this.remove, icon: 'close'},
{name: 'up', action: this.moveUp, icon: 'arrow-up'},
{name: 'down', action: this.moveUp, icon: 'arrow-down'}
];
var toggleButton = {name: 'toggle'};
toggleButton.state = ko.observable(false); // closed by default
toggleButton.action = function() { toggleButton.state(!toggleButton.state()); };
toggleButton.icon = ko.computed(function() { return toggleButton.state() ? 'minus' : 'plus';});
this.toolbar.push(toggleButton);
}
ko.applyBindings(new app());
.closed { overflow: hidden; left: -2000px; }
.open { left: 0; }
div { transition: .3s all ease-in-out; position: relative;}
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<i>( only the last (toggle) button working for demo )</i>
<span data-bind="foreach: toolbar">
<button type="button" data-bind="attr: { title: name }, click: action">
<i data-bind="attr: { class: 'fa fa-' + ko.unwrap(icon) }"></i>
</button>
</span>
<h4>Comments</h4>
<div data-bind="css: { 'open': toolbar[4].state, 'closed': !toolbar[4].state() }">
Support requests, bug reports, and off-topic comments will be deleted without warning.
Please do post corrections and additional information/pointers for this article below. We aim to move corrections into our documentation as quickly as possible. Be aware that your comments may take some time to appear.
If you need specific help with your account, please contact our support team.
</div>

Durandal 2.0 - Update the value of an observable in the view

I'm new to Durandal, my question has probably a very simple issue.
I load a list into a dropdown and the current value on the link which display the dropdown,
And the value of the link which display the dropdown is not updated correctly when an other value is selected.
But actually, I can't set the value of the observable in the select function.
View Model
var self = this;
self.system = require('durandal/system');
IPsKeys: ko.observableArray([]),
ipKeys: ko.observable(""),
activate: function (context) {
var that = this;
that.IPsKeys([]);
that.ipKeys("");
return $.when(
service.getIPSbyClientId(context.clientId).then(function (json) {
$.each(json, function (Index, Value) {
var ClientLobUWYear = {
NameLob: Value.LineOfBusiness.Name,
NameUWYear: Value.UnderwritingYear
};
that.IPsKeys().push(ClientLobUWYear);
// HERE MY VALUE IS GOOD UPDATING AND THE BINDING WORK
if (Index=== 0) {
that.ipKeys(ClientLobUWYear);
}
});
})
).then(function () {
//do some other datacontext calls for stuff used directly and only in view1
});
},
select: function (item) {
this.ipKeys = {
IdClient: item.IdClient,
IdLob: item.IdLob,
NameLob: item.NameLob,
NameUWYear: item.NameUWYear
};
/** PROBLEMS HERE **/
/** Uncaught TypeError: undefined is not a function **/
this.ipKeys(ClientLobUWYear);
},
View
<a id="select_lob-UWYear" class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="controls_value" data-bind="text: ipKeys().NameLob">ALOB</span>
<span class="controls_value" data-bind="text: ipKeys().NameUWYear">AYEAR</span>
</a>
<ul id="dropdown_year" class="dropdown-menu" data-bind="foreach: IPsKeys().sort(sortByLobYear)">
<li>
<a href="#" data-bind="click: $parent.select">
<span class="controls_value" data-bind="text: NameLob">Cargo</span>
<span class="controls_value" data-bind="text: NameUWYear">2014</span>
</a>
</li>
</ul>
Thanks a lot
The way you update an observable is like this:
var someObservable = ko.observable(""); //setting to "";
someObservable("Something else"); //updating to "Something else"
Not like this (which you are doing above)
var someObservable = ko.observable(""); //setting to "";
someObservable = "Something else";
This is overwriting someObservable with a string of value "Something else" and so is no longer an observable which is why it will not update the ui.
[JS Fiddle showing how to set observables.]

How do I used Knockout's "hasfocus" Click-to-Edit (Example 2) on a page that has multiple field:value pairs

How do I used Knockout's "hasfocus" binding in Click-to-Edit (Example 2) on a page that has multiple field:value pairs? I have a page for View Customer Details, and I want to have this capability to edit upon double click.
You need to create an array of PersonViewModels and foreach loop them in the view. To reuse the example on the knockout page the code could look like this:
(function () {
function PersonViewModel(name) {
// Data
this.name = ko.observable(name);
this.editing = ko.observable(false);
// Behaviors
this.edit = function() { this.editing(true) }
}
function ViewModel(personModels) {
this.persons = ko.observableArray(personModels);
}
var personModels = [
new PersonViewModel('Bert'),
new PersonViewModel('James'),
new PersonViewModel('Eddy')
];
ko.applyBindings(new ViewModel(personModels));
})();
And the view:
<div data-bind="foreach: persons">
<p>
Name:
<b data-bind="visible: !editing(), text: name, click: edit"> </b>
<input data-bind="visible: editing, value: name, hasfocus: editing" />
</p>
<p><em>Click the name to edit it; click elsewhere to apply changes.</em></p>
</div>
Here's a jsfiddle demo: http://jsfiddle.net/danne567/gTHpu/

Filter users by one keyword in a nested observableArray

I am trying to filter my users observableArray which has a nested keywords observableArray
based on a keywords observableArray on my viewModel.
When I try to use ko.utils.arrayForEach I get a stack overflow exception. See the code below, also posted in this jsfiddle
function User(id, name, keywords){
return {
id: ko.observable(id),
name: ko.observable(name),
keywords: ko.observableArray(keywords),
isVisible: ko.dependentObservable(function(){
var visible = false;
if (viewModel.selectedKeyword() || viewModel.keywordIsDirty()) {
ko.utils.arrayForEach(keywords, function(keyword) {
if (keyword === viewModel.selectedKeyword()){
visible = true;
}
});
if (!visible) {
viewModel.users.remove(this);
}
}
return visible;
})
}
};
function Keyword(count, word){
return{
count: ko.observable(count),
word: ko.observable(word)
}
};
var viewModel = {
users: ko.observableArray([]),
keywords: ko.observableArray([]),
selectedKeyword: ko.observable(),
keywordIsDirty: ko.observable(false)
}
viewModel.selectedKeyword.subscribe(function () {
if (!viewModel.keywordIsDirty()) {
viewModel.keywordIsDirty(true);
}
});
ko.applyBindings(viewModel);
for (var i = 0; i < 500; i++) {
viewModel.users.push(
new User(i, "Man " + i, ["Beer", "Women", "Food"])
)
}
viewModel.keywords.push(new Keyword(1, "Beer"));
viewModel.keywords.push(new Keyword(2, "Women"));
viewModel.keywords.push(new Keyword(3, "Food"));
viewModel.keywords.push(new Keyword(4, "Cooking"));
And the View code:
<ul data-bind="template: { name: 'keyword-template', foreach: keywords }"></ul><br />
<ul data-bind="template: { name: 'user-template', foreach: users }"></ul>
<script id="keyword-template" type="text/html">
<li>
<label><input type="radio" value="${word}" name="keywordgroup" data-bind="checked: viewModel.selectedKeyword" /> ${ word }<label>
</li>
</script>
<script id="user-template" type="text/html">
<li>
<span data-bind="visible: isVisible">${ $data.name }</span>
</li>
</script>
Your isVisible dependentObservable has created a dependency on itself and is recursively trying to evaluate itself based on this line:
if (!visible) {
viewModel.users.remove(this);
}
So, this creates a dependency on viewModel.users, because remove has to access the observableArray's underlying array to remove the user. At the point that the array is modified, subscribers are notified and one of the subscribers will be itself.
It is generally best to not change the state of any observables in a dependentObservable. you can manually subscribe to changes to a dependentObservable and makes your changes there (provided the dependentObservable does not depend on what you are changing).
However, in this case, I would probably instead create a dependentObservable at the viewModel level called something like filteredUsers. Then, return a version of the users array that is filtered.
It might look like this:
viewModel.filteredUsers = ko.dependentObservable(function() {
var selected = viewModel.selectedKeyword();
//if nothing is selected, then return an empty array
return !selected ? [] : ko.utils.arrayFilter(this.users(), function(user) {
//otherwise, filter on keywords. Stop on first match.
return ko.utils.arrayFirst(user.keywords(), function(keyword) {
return keyword === selected;
}) != null; //doesn't have to be a boolean, but just trying to be clear in sample
});
}, viewModel);
You also should not need the dirty flag, as dependentObservables will be re-triggered when any observables that they access have changed. So, since it accesses selectedKeyword, it will get re-evaluated whenever selectedKeyword changes.
http://jsfiddle.net/rniemeyer/mD8SK/
I hope that I properly understood your scenario.

Categories