Accessing objects within viewmodel Knockout - javascript

I'm using knockout for a single page app that does some basic calculations based on several inputs to then populate the value of some html . In an attempt to keep my html concise I've used an array of objects in my viewModel to store my form. I achieved the basic functionality of the page however I wish to add a 'display' value to show on html that has formatted decimal points and perhaps a converted value in the future.
I'm not sure of a 'best practices' way of accessing the other values of the object that I'm currently 'in'. For example: If I want my display field to be a computed value that consists of the value field rounded to two decimal places.
display: ko.computed(function()
{
return Math.round(100 * myObj.value())/100;
}
I've been reading through the documentation for knockout and it would appear that managing this is a common problem with those new to the library. I believe I could make it work by adding the computed function outside of the viewmodel prototype and access the object by
viewModel.input[1].value()
However I would imagine there is a cleaner way to achieve this.
I've included a small snippet of the viewModel for reference. In total the input array contains 15 elements. The HTML is included below that.
var ViewModel = function()
{
var self = this;
this.unitType = ko.observable('imperial');
this.input =
[
{
name: "Test Stand Configuration",
isInput: false
},
{
name: "Charge Pump Displacement",
disabled: false,
isInput: true,
unitImperial: "cubic inches/rev",
unitMetric: "cm^3/rev",
convert: function(incomingSystem)
{
var newValue = this.value();
if(incomingSystem == 'metric')
{
//switch to metric
newValue = convert.cubicinchesToCubiccentimeters(newValue);
}
else
{
//switch to imperial
newValue = convert.cubiccentimetersToCubicinches(newValue);
}
this.value(newValue);
},
value: ko.observable(1.4),
display: ko.computed(function()
{
console.log(self);
}, self)
}
]
};
__
<!-- ko foreach: input -->
<!-- ko if: $data.isInput == true -->
<div class="form-group">
<div class="col-sm-6">
<label class="control-label" data-bind="text: $data.name"></label>
</div>
<div class="col-sm-6">
<div class="input-group">
<!-- ko if: $data.disabled == true -->
<input data-bind="value: $data.value" type="text" class="form-control" disabled>
<!-- /ko -->
<!-- ko if: $data.disabled == false -->
<input data-bind="value: $data.value" type="text" class="form-control">
<!-- /ko -->
<!-- ko if: viewModel.unitType() == 'imperial'-->
<span data-bind="text: $data.unitImperial" class="input-group-addon"></span>
<!-- /ko -->
<!-- ko if: viewModel.unitType() == 'metric' -->
<span data-bind="text: $data.unitMetric" class="input-group-addon"></span>
<!-- /ko -->
</div>
</div>
</div>
<!-- /ko -->
<!-- ko if: $data.isInput == false -->
<div class="form-group">
<div class="col-sm-6">
<h3 data-bind="text: $data.name"></h3>
</div>
</div>
<!-- /ko -->

If you want to read/ write to & from the same output, #Aaron Siciliano's answer is the way to go. Else, ...
I'm not sure of a 'best practices' way of accessing the other values of the object that > I'm currently 'in'. For example: If I want my display field to be a computed value that consists of the value field rounded to two decimal places.
I think there's a misconception here about what KnockoutJS is. KnockoutJS allows you to handle all your logic in Javascript. Accessing the values of the object you are in is simple thanks to Knockout's context variables: $data (the current context, and the same as JS's this), $parent (the parent context), $root(the root viewmodel context) and more at Binding Context. You can use this variables both in your templates and in your Javascript. Btw, $index returns the observable index of an array item (which means it changes automatically when you do someth. wth it). In your example it'd be as simple as:
<span data-bind="$data.display"></span>
Or suppose you want to get an observable w/e from your root, or even parent. (Scenario: A cost indicator that increases for every item purchased, which are stored separately in an array).
<span data-bind="$root.totalValue"></span>
Correct me if I'm wrong, but given that you have defined self only in your viewmodel, the display function should output the whole root viewmodel to the console. If you redefine a self variable inside your object in the array, self will output that object in the array. That depends on the scope of your variable. You can't use object literals for that, you need a constructor function (like the one for your view model). So you'd get:
function viewModel() {
var self = this;
self.inputs = ko.observableArray([
// this builds a new instance of the 'input' prototype
new Input({initial: 0, name: 'someinput', display: someFunction});
])
}
// a constructor for your 15 inputs, which takes an object as parameter
function Input(obj) {
var self = this; // now self refers to a single instance of the 'input' prototype
self.initial = ko.observable(obj.initial); //blank
self.name = obj.name;
self.display = ko.computed(obj.fn, this); // your function
}
As you mentioned, you can also handle events afterwards, see: unobtrusive event handling. Add your event listeners by using the ko.dataFor & ko.contextFor methods.

It appears as though KnockoutJS has an example set up on its website for this exact scenario.
http://knockoutjs.com/documentation/extenders.html
From reading that page it looks as though you can create an extender to intercept an observable before it updates and apply a function to it (to format it for currency or round or perform whatever changes need to be made to it before it updates the ui).
This would probably be the closest thing to what you are looking for. However to be completely honest with you i like your simple approach to the problem.

Related

KoJs: bind a dynamic number of text boxes to elements of an array

I have a front-end which allows for adding and removing of text boxes suing the foreach binding. A text box looks something like this
<div id="dynamic-filters" data-bind="foreach: filterList">
<p>
<input type="text" data-bind="textInput: $parent.values[$index()], autoComplete: { options: $parent.options}, attr: { id : 'nameInput_' + $index() }"/>
</p>
</div>
What I want to do, as shown in the code above is to bind each of these dynamically generated text boxes to an element in the array using the $index() context provided by knockout.js
However it doesn't work for me, my self.values=ko.observableArray([]) doesn't change when the text boxes change.
My question is, if I want to have a way to bind these dynamically generated text boxes, is this the right way to do it? If it is how do I fix it? If it's not, what should I do instead?
Thanks guys!
EDIT 1
the values array is an observable so I thought I should unwrap it before use. I changed the code to
<input type="text" data-bind="textInput: $parent.values()[$index()], autoComplete: { options: $parent.options}, attr: { id : 'nameInput_' + $index() }"/>
This works in a limited way. When I add or change the content of text boxes, the array changes accordingly. However when I delete an element it fails in two ways:
If I delete the last item, the array simply doesn't change
If I delete an item in between, everything is shifted back
I suppose I have to add a function that changes the text-input value before destroying the text box itself.
Any help or advice on how to do this?
I would suggest taking the array of values and mapping it to some kind of model first, then dumping it into the filterList ko.observableArray. It can be as complex or as simple as need be.
That way you have direct access to those properties at the ko foreach: level instead of having to do the goofy index access.
I've added a simple knockout component example as well to show you what can be achieved.
var PageModel = function() {
var self = this;
var someArrayOfValues = [{label: 'label-1', value: 1},{label: 'label-2', value: 2},{label: 'label-3', value: 3},{label: 'label-4', value: 4}];
this.SimpleInputs = ko.observableArray(_.map(someArrayOfValues, function(data){
return new SimpleInputModel(data);
}));
this.AddSimpleInput = function(){
self.SimpleInputs.push(new SimpleInputModel({value:'new val', label:'new label'}));
};
this.RemoveSimpleInput = function(obj){
self.SimpleInputs.remove(obj);
}
}
var SimpleInputModel = function(r) {
this.Value = ko.observable(r.value);
this.Label = r.label;
};
var SimpleInputComponent = function(params){
this.Id = makeid();
this.Label = params.label;
this.Value = params.value;
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
}
ko.components.register('input-component', {
viewModel: SimpleInputComponent,
template: '<label data-bind="text: Label, attr: {for: Id}"></label><input type="text" data-bind="textInput: Value, attr: {id: Id}" />'
})
window.model = new PageModel();
ko.applyBindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: SimpleInputs -->
<h3>Simple Inputs</h3>
<!-- ko foreach: SimpleInputs -->
<input-component params="value: Value, label: Label"></input-component>
<button data-bind="click: $parent.RemoveSimpleInput">X</button>
<br>
<!-- /ko -->
<!-- /ko -->
<button data-bind="click: AddSimpleInput">Add Input</button>
EDIT (7/16/2020):
Mind explaining this without requiring lodash? I literally googled "how to lodash map using plain javascript". Excellent answer otherwise! – CarComp
In this scenario the lodash _.map method could be overkill unless you are executing the script in an environment that does not have native support for the vanilla array map method. If you have support for the vanilla method, go ahead and use that. The map method essentially iterates over each array using the method it is handed to return a transformed array of the original items. Implementation of vanilla code would look like so.
this.SimpleInputs = ko.observableArray(someArrayOfValues.map(function(data) {
return new SimpleInputModel(data);
}));
Here we are taking the values of someArrayOfValues and telling it to use each item to build a new SimpleInputModel and return it using that item data. [SimpleInputModel, SimpleInputModel, SimpleInputModel, SimpleInputModel] is what the new array turns into after mapping. Each of these items has all the functionality described in the SimpleInputModel class, Value and Label.
So with the new array you could, if you wanted, access the values like this as well self.SimpleInputs[0].Value() or self.SimpleInputs[0].Label
Hope that helps to clarify.

Show different content if 'ko with' is not displayed

I'm using the following knockout code to display properties from an object.
Using the with i can check if the properties in this object exist.
<!-- ko with: Bunk1 -->
<div data-bind="css: Color">
<div class="row no-margin">
<div>
<div data-bind="text: Name"></div>
<div data-bind="text: FirstName"></div>
</div>
</div>
</div>
<!-- /ko -->
This is the model:
var viewModel = function () {
var self = this;
self.Bunk1 = ko.observable();
self.Bunk2 = ko.observable();
...
...
// 'val' is loaded with $.ajax
// this code might not be executed and Bunk1 can fail to initialize.
var model = new BunkModel();
model.initModel(val);
self.Bunk1(model);
...
}
function BunkModel() {
var self = this;
self.Color = ko.observable();
self.Name= ko.observable();
self.FirstName= ko.observable();
self.initModel = function (values) {
self.Color(self.mapColor(values.color));
self.Name(values.name);
self.FirstName(values.firstName);
}
}
What i would like to do is to display an alternative div if there is no data, something like an else to the ko with. How can i bind the object properties but display alternative data if they don't exist.
When creating a new observable without passing a value, its value will be undefined. This means you can simply add a conditional block below the existing with block:
<!-- ko if: Bunk1() === undefined -->
content here
<!-- /ko -->
Note that you need to use parentheses when doing a comparison like this, Bunk1 === undefined would check if the observable itself is undefined instead of its underlying value.
In addition to #Stijn answer.
You can use "ifnot" binding:
<!-- ko ifnot: Bunk1 -->
content here
<!-- /ko -->

knockout 'click' binding not working

I am trying to bind a click event to a list item. When I click on the list item below, it should fire up the updateCurrent function in the javascript, but it doesn't do anything.
note: I have used $parent.updateCurrent as I am in the currentCat context when I call the function and the updateCurrent function is in the ViewModel context.
HTML:
<div id="wrap" data-bind="with: currentCat">
<div id="names">
<ul data-bind="foreach: $parent.catNames">
<!--Here, clicking on name doesn't fire updateCurrent-->
<li data-bind="text: $data, click: $parent.updateCurrent"></li>
</ul>
</div>
</div>
JS:
var viewModel = function() {
var self = this;
this.catNames = ko.observableArray([]);
this.catList = ko.observableArray([]);
//cats is defined as a simple array of objects, having name
cats.forEach(function(catObject) {
self.catList.push(new cat(catObject));
self.catNames.push(catObject.name);
});
//initially, set the currentCat to first cat
this.currentCat = ko.observable(this.catList()[0]);
//should run when the user click on the cat name in the list
this.updateCurrent = function() {
console.log("hello");
}
};
I don't get any error when I click on the list name, but console doesn't log anything.
I believe I am not using the context properly, but can't figure out the exact issue here. Any help will be appreciated.
When you say $parent.catNames, you are referring to the ViewModel because it is an owned property of the immediate parent in the hierarchy. With the foreach binding, you are within a new context; therefore in $parent.updateCurrent, the immediate parent in the hierarchy becomes the item in catNames array.
You can use $root in this case as Viktor has mentioned but the safest and proper way to achieve this functionality is to climb the hierarchy one level at a time to obtain $parents[1].
$parent is equal to $parents[0] which is one of the catNames. $parents[1] will refer to the ViewModel.
Why not use $root?
Knockout will maintain your DOM and binding context much deeper than may be readily apparent. In template bindings, the $root context may refer to an object that isn't even in the HTML template!
<div data-bind="template: { name: 'sample', data: catNames }"></div>
<script type='text/html' id='sample'>
<!-- ko foreach: $data -->
<span data-bind="text: 'Cat ' + $index + ' of ' + $parents[0].length"></span>
Returns "Cat 1 of 10"
<!-- /ko -->
<!-- ko foreach: $data -->
<span data-bind="text: 'Cat ' + $index + ' of ' + $root.length"></span>
Return "Cat 1 of undefined" because ViewModel has no length property!
<!-- /ko -->
</script>
Binding context documentation: http://knockoutjs.com/documentation/binding-context.html
You are inside two levels of context. The with binding indicates that $data inside that div is currentCat. The foreach provides another level of context. $parent doesn't refer to the parent of an object, but the context outside this context. You could use $parents[1].
When you say $parent.catNames, you're only inside the with context, so it does refer to catNames in ViewModel, since there's no other enclosing context. But where you say $parent.updateCurrent, you're jumping out of the foreach context up to the with context. And you wanted to jump one more.

Knockout: Best way to bind visibility to both item and a parent property?

I am creating an edit screen where I want people to delete items from a list. The list is displayed normally, until the "controller" object goes into edit mode. Then the user can delete items. Items should be flagged for deletion and displayed as such, then when the user saves the edit, they are deleted and the server notified.
I actually have this all working, but the only way I could do it was using literal conditions in the bindings, which looks ugly and I don't really like. Is there a better way of doing it?
Working Fiddle: http://jsfiddle.net/L1e7zwyv/
Markup:
<div id="test">
<a data-bind="visible: IsViewMode, click: edit">Edit</a>
<a data-bind="visible: IsEditMode, click: cancel">Cancel</a>
<hr/>
<ul data-bind="foreach: Items">
<li data-bind="css: CssClass">
<span data-bind="visible: $parent.IsViewMode() || $data._Deleting(), text: Value"></span>
<!-- ko if: $parent.IsEditMode() && !$data._Deleting() -->
<input type="text" data-bind="value: Value"/>
<a data-bind="click: $parent.deleteItem">Del</a>
<!-- /ko -->
</li>
</ul>
</div>
Code:
function ItemModel(val)
{
var _this = this;
this.Value = ko.observable(val);
this._Deleting = ko.observable();
this.CssClass = ko.computed(
function()
{
return _this._Deleting() ? 'deleting' : '';
}
);
}
function ManagerModel()
{
var _this = this;
this.Items = ko.observableArray([
new ItemModel('Hell'),
new ItemModel('Broke'),
new ItemModel('Luce')
]);
this.IsEditMode = ko.observable();
this.IsViewMode = ko.computed(function() { return !_this.IsEditMode(); });
this.edit = function(model, e)
{
this.IsEditMode(true);
};
this.cancel = function(model, e)
{
for(var i = 0; i < _this.Items().length; i++)
_this.Items()[i]._Deleting(false);
this.IsEditMode(false);
};
this.deleteItem = function(model, e)
{
model._Deleting(true);
};
}
ko.applyBindings(new ManagerModel(), document.getElementById('test'));
you could:
wrap another span around to separate the bindings but this would be less efficient.
use both a visible: and if: binding on the same element to achieve the same functionality,
write a function on the itemModel isVisible() accepting the parent as an argument making your binding visible: $data.isVisible($parent).
Afterthought: If this comes up in multiple places you could write a helper function to combine visibility bindings
// reprisent variables from models
var v1 = false;
var v2 = false;
var v3 = false;
// Helper functions defined in main script body - globally accessible
function VisibilityFromAny() {
var result = false;
for(var i = 0; i < arguments.length; i++ ) result |= arguments[i];
return Boolean(result);
}
function VisibilityFromAll() {
var result = true;
for(var i = 0; i < arguments.length; i++ ) result &= arguments[i];
return Boolean(result);
}
// represent bindings
alert(VisibilityFromAny(v1, v2, v3));
alert(VisibilityFromAll(v1, v2, v3));
The third option is the most popular technique with MVVM aficionados like yourself for combining variables in a single binding from what I've seen, it makes sense and keeps all the logic away from the view markup in the view models.
Personally I like the syntax you have at present, (even though I count myself amongst the MVVM aficionado gang as well) this clearly shows in the view markup that the visibility of that element is bound to 2 items rather then hiding these details in a function.
I try to think of view models as a model for my view, not just a place where logic resides. When possible I also try to move complex logic back the view model and use descriptive names for my variables so the code is more readable.
I would suggest adding this to your view model -
var isViewable = ko.computed(function () { return IsViewMode() || _Deleting(); });
var isEditable = ko.computed(function() { return IsEditMode() && !_Deleting(); });
And in your view -
<li data-bind="css: CssClass">
<span data-bind="visible: isViewable, text: Value"></span>
<!-- ko if: isEditable -->
<input type="text" data-bind="value: Value"/>
<a data-bind="click: $parent.deleteItem">Del</a>
<!-- /ko -->
</li>
This cleans the bindings up and allows you to more easily adjust the logic without having to do many sanity checks in your view and view model both. Also I personally name variables that return a boolean such as this as isWhatever to help be more descriptive.
The benefit is that as your view and view model grow larger you can keep the DOM clean of clutter and also your view model becomes testable.
Here is a 'code complete' version of your fiddle with this added -
http://jsfiddle.net/L1e7zwyv/3/

Show default value when Knockout observable undefined or JS disabled

Using Knockout.js, is there a way to have an element's original content show if the observable bound to it is undefined?
<p data-bind="text: message">Show this text if message is undefined.</p>
<script>
function ViewModel() {
var self = this;
self.message = ko.observable();
};
ko.applyBindings(new ViewModel());
</script>
I know there are workarounds using visible, hidden or if but I find those too messy; I don't want the same element written out twice, once for each condition.
Also, I don't want to use any sort of default observable values. Going that route, if JS is disabled then nothing shows up. Same for crawlers: they would see nothing but an empty <p> tag.
To summarize, I want to say "Show this message if it exists, otherwise leave the element and its text alone."
The reasoning behind this is that I want to first populate my element using Razor.
<p data-bind="text: message">#Model.Message</p>
And then, in the browser, if JS is enabled, I can do with it as I please. If, however, there is no JS or the user is a crawler, they see, at minimum, the default value supplied server side via Razor.
You can simply use the || operator to show a default message in case message is undefined. Plus put the default text as content:
<p data-bind="text: message() || '#Model.Message' ">#Model.Message</p>
If javascript is disabled, the binding will be ignored and you will have the content displayed instead.
JSFiddle
Try this out
<p data-bind="text: message"></p>
<script>
function ViewModel() {
var self = this;
self.text = ko.observable();
self.message = ko.computed(function(){
if(self.text() != undefined){
return self.text();
}else{
return "Show this text if message is undefined.";
}
});
};
ko.applyBindings(new ViewModel());
</script>
You can set a default value like that in a number of ways, simplest way is to set the default observable value, as your JS file will be incorporated in to your HTML and will be able to access #Model.Message, so you can set a default value:
self.message = ko.observable(#Model.Message);
Here are a few other variations:
var viewModel = {
message: ko.observable(),
message1: ko.observable('Show this text if message is undefined.')
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h2>Option 1</h2>
<i>Set default value of observable: self.message1 = ko.observable(#Model.Message);</i>
<p data-bind="text: message1"></p>
<h2>Option 2</h2>
<i>Check for undefined and replace</i>
<p data-bind="text: message() ? message : message1"></p>
<h2>Option 3</h2>
<i>Use KO if syntax to display content if defined/undefined</i>
<!-- ko if: message() -->
<p data-bind="text: message"></p>
<!-- /ko -->
<!-- ko ifnot: message() -->
<p data-bind="text: message1"></p>
<!-- /ko -->

Categories

Resources