ko.computed property to determine visibility not working - javascript

In my KncokoutJS ViewModel, I have the follow computed property:
self.SelectedUserHasRoles = ko.computed(function () {
if (self.isLoaded()) {
return self.selectedUser().roles().length > 0;
}
return false;
});
And in my HTML, I have the following:
<!-- ko if: isLoaded() -->
<!-- ko if: !SelectedUserHasRoles -->
<div>
<p>User has no Roles.</p>
</div>
<!-- /ko -->
<!-- ko if: SelectedUserHasRoles -->
<div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
<div class="role-token" data-bind="text: Name"></div>
</div>
<!-- /ko -->
<!-- /ko -->
In my code, I was to say this:
If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'
All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!
What am I doing wrong? I've created a screencast to make things easier to understand.

When you want to negate an observable or computed value in a binding, you have to call it explicitly:
<!-- ko if: !SelectedUserHasRoles() -->
In the case of the if binding, there's also the ifnot counterpart:
<!-- ko ifnot: SelectedUserHasRoles -->
I think it's useful to understand why this is needed, since I see it happening a lot.
You could see the data-bind attribute as a comma separated string of key value pairs. Knockout wraps each of the values in a function, which it calls the valueAccessor.
Essentially, you'll go from:
data-bind="if: SelectedUserHasRoles"
to
{
"if": function() { return SelectedUserHasRoles }
}
SelectedUserHasRoles is an observable instance, which evaluates as truthy. When you negate this value using an !, it will always be false.
var myObs = ko.observable("anything");
var valueAccessor = function() { return myObs; };
var valueAccessorNeg = function() { return !myObs; };
console.log(valueAccessor()); // Returns the observable
console.log(valueAccessorNeg()); // Always prints false
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
The valueAccessor function is passed to the init method of a binding. Usually, it is retrieved by calling it, and then unwrapped. Because the unwrap utility doesn't care about whether you pass it an observable or a plain value, you'll not see any errors when you make this mistake.
var myObs = ko.observable(false);
var va1 = function() { return myObs; };
var va2 = function() { return !myObs; };
var va3 = function() { return !myObs(); };
console.log(ko.unwrap(va1())); // false
console.log(ko.unwrap(va2())); // always false
console.log(ko.unwrap(va3())); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
I hope this small peek under the hood might help you (and others that have made this mistake) to be able to determine when the () are needed in the future.

Because you are not binding to a variable but to an expression, you need to add parenthesis here:
<!-- ko if: !SelectedUserHasRoles() -->
//^^ here
See the following snippet
function CreateVM() {
var self = this;
this.isTrue = ko.observable(false);
this.selectedUser = ko.observable();
this.isLoaded = ko.observable();
self.SelectedUserHasRoles = ko.computed(function () {
if (self.isLoaded()) {
return self.selectedUser().roles().length > 0;
}
return false;
});
}
var vm = new CreateVM();
ko.applyBindings(vm);
var userWithRoles = { roles: ko.observableArray([1,2]) };
var userWithoutRoles = { roles: ko.observableArray([]) };
vm.selectedUser(userWithoutRoles);
vm.isLoaded(true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: isLoaded() -->
<!-- ko if: !SelectedUserHasRoles() -->
<div>
<p>User has no Roles.</p>
</div>
<!-- /ko -->
<!-- ko if: SelectedUserHasRoles -->
<div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
<div class="role-token" data-bind="text: $data"></div>
</div>
<!-- /ko -->
SelectedUserHasRoles: <span class="role-token" data-bind="text: SelectedUserHasRoles"></span>
<!-- /ko -->
See user3297291's answer for more details.

You have the same check for isLoaded() twice, actually
<!-- ko if: isLoaded() -->
<!-- ko if: !SelectedUserHasRoles -->
if isLoaded() evalutes to false, your SelectedUserHasRoles() won't even be evaluated.

Related

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 -->

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 -->

Accessing objects within viewmodel Knockout

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.

Knockout computed is triggered too many times

I have a viewModel and a template which renders data based on an if condition:
<!-- ko template: { data: selectedFolder, if: isTemplateVisible, name: 'selectedFoldersProperties-template' } --><!-- /ko -->
I think that the template is being rendered 4 times consecutively, and one of the reasons is that isTemplateVisible is a ko.computed.
If i change if: isTemplateVisible to if: selectedFolder, then the template gets rendered 2 times consecutively.
I have a jsfiddle demo.
You will see that "hit" is output-ed for 4 times after the button has been pressed.
Is there a reason why the function gets called so many times?
<button id="button" type="button">
Set folder
</button>
<div>
<!-- ko template: { data: selectedFolder, if: isTemplateVisible, name: 'selectedFoldersProperties-template' } --><!-- /ko -->
</div>
<script type="text/html" id="selectedFoldersProperties-template">
<span data-bind="text: FolderName"></span>
<ul data-bind="foreach: $root.getFiles($data)">
<li>
<span data-bind="text: FileName"></span>
</li>
</ul>
</script>
var viewModel = {
selectedFolder: ko.observable(null),
getFiles: function(folderData) {
console.log("hit");
return [
{ FileName: "File 1" },
{ FileName: "File 2" }
];
}
};
viewModel.isTemplateVisible = ko.computed(function(){
return this.selectedFolder();
}, viewModel);
ko.applyBindings(viewModel);
document.getElementById("button").onclick = function() {
viewModel.selectedFolder({
FolderName: "Folder 1"
});
};
Your isTemplateVisible has a dependency on selectedFolder so that makes you template to re-render.
change isTemplateVisible to not be a computed first:
viewModel.isTemplateVisible = function(){
return this.selectedFolder();
};
and then change your if binding on the template to execute the value out:
if: isTemplateVisible()
then your tmeplate won't run twice due to the dependency.
Here is the working fiddle
Alternatively
You can simply the whole thing by removing the iftemplateisvisible stuff:
<button id="button" type="button">
Set folder
</button>
<div>
<!-- ko if: selectedFolder -->
<!-- ko template: { data: selectedFolder, name: 'selectedFoldersProperties-template' } --><!-- /ko -->
<!-- /ko -->
</div>
<script type="text/html" id="selectedFoldersProperties-template">
<span data-bind="text: FolderName"></span>
<ul data-bind="foreach: $root.getFiles($data)">
<li>
<span data-bind="text: FileName"></span>
</li>
</ul>
</script>
and viewmodel:
var viewModel = {
selectedFolder: ko.observable(null),
getFiles: function(folderData) {
console.log("hit");
return [
{ FileName: "File 1" },
{ FileName: "File 2" }
];
}
};
ko.applyBindings(viewModel);
document.getElementById("button").onclick = function() {
viewModel.selectedFolder({
FolderName: "Folder 1"
});
};
Here is fiddle for the second solution
Further clarification to why you have this issue
If you want to delve deeper in what's going wrong I have created another fiddle which is time stamping your template:
So what is happening is that on the same comment binding you have an observable and a computed which are interdependent, therefore they are causing your template to render twice inseatd of only one time.
So you either as I suggested need to separate them on different bindings so one has resolved by the time you are evaluating the other or you eliminate one of them.
If you change your binding to not have inter-dependency and be for example:
if: selectedFolder(), data: selectedFolder
Then the loop won't occur as you don't have two things dependent on each other and responsible for rendering the template.
Based on this also Throttle is not going to help you as all it does it to delay the value change of an observable which would delay your first render, followed by the interdependency loop caused by cross referencing.
getFiles function runs twice due to being a self executing function on your binding. It tuns once when it's being placed on the page and again when it is its turn to run inside foreach.
This can be demonstrated here where you can see that the callers of your getFiles function are both function (){return $root.getFiles() } from your template.
If you change that function to be foreach: $root.getFiles without the parenthesis and make getFiles an observableArray so it gets resolved by knockout then you won't have the twice execution issue.
That is because you are having foreach binding.
This code <ul data-bind="foreach: $root.getFiles($data)"> will cause to compute it 4 times.
Hope its clear

Knockoutjs throws exception when trying to create series of unordered lists

I'm attempting to create a series of <ul> tags using the foreach: context. The goal is to iterate through the list, and start a new <ul> for every 4th item. My code so far is:
<ul data-bind="foreach: Areas">
<li><span>
<input type="checkbox" data-bind="value: AreaId, checked: $root.AreasImpacted" />
<label><span data-bind="text: Name"></span></label>
</span></li>
<!-- ko if: ($index() % 4 == 0) -->
</ul><ul>
<!-- /ko -->
</ul>
When I do this, I get the exception:
Microsoft JScript runtime error: Cannot find closing comment tag to
match: ko if: ($index() % 4 == 0)
It seems to not like the </li><li> content within the if comment block, probably because the DOM parser is scratching its head on how to actually parse this. If I change it to:
<!-- ko if: ($index() % 4 == 0) -->
<li>Fake!</li>
<!-- /ko -->
Then it'll work perfectly (that is, create a fake <li> every 4th element.
I'm open to other ideas of accomplishing this as well. Thanks!
Yeah, the initial DOM (before Knockout activates) is illegal, and Knockout doesn't work by pasting HTML into the DOM, it actually copies it into a javascript DOM object, which it inserts into the DOM. </ul><ul> isn't a legal object, so Knockout won't be able to turn it into a template. Even if it could, the foreach binding is on the original <ul>, not the new one started by the if, so the Knockout code that added items would still be operating on the first list.
So, in summation, Knockout's foreach and template bindings don't work by building HTML as if it's a string.
You will need a more complex solution.
Something like this would work, but I don't know if this is still what you are going for:
<!-- ko foreach: { data: chunkedList, as: 'areas' } -->
<span>SPLIT!</span>
<ul data-bind="foreach: areas">
<li><span data-bind="text: name"></span></li>
</ul>
<!-- /ko -->
var Viewmodel = function(data) {
var self = this;
self.items = ko.observableArray(data);
self.chunkedList = ko.computed(function() {
var result = [];
var chunk = [];
self.items().forEach(function(item, index) {
if (index % 4 === 0) {
chunk = [];
result.push(chunk);
};
chunk.push(item);
});
return result;
});
};

Categories

Resources