Knockout JS arbitrary objects binding - javascript

i'm very new to knockout js and i'm trying my hands out on examples so i have this
<script>
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries : ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]),
selectedCountry : ko.observable() // Nothing selected by default
};
$(function(){ko.applyBindings(viewModel)});
</script>
and in the view
<p>Your country:
<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
my question is i want the drop down to have a pre-selected value at initialization so i tried this
selectedCountry : ko.observable(new Country("UK", 65000000))
but its not working "Choose..." still appears as the pre-selected optionsText instead of "Uk" then i tried
selectedCountry : ko.observable(availableCountries[0])
but i keep getting this error
"Uncaught TypeError: Cannot read property '0' of undefined "
what am i doing wrongly and how do i fix it?

after you define the viewModel object, add the following:
viewModel.selectedCountry(viewModel.availableCountries()[0]);
you cant reference a value on an object as its being declared (at least i dont think you can), so you would need to do the assignment after the fact.
another option is to define your viewModel as a function:
var viewModel = function (){
var self = this;
self.availableCountries = ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]);
self.selectedCountry = ko.observable(self.availableCountries()[0])
};

I believe the solution to this is to set your selected value to "UK". As the value binding reads just the value not the entire object.
So when you set the object at index 0 that item isn't recognized as a value.
HTH

Related

Unable to get optionsValue to work with dependent dropdowns and the Knockout mapping plugin

I am a database developer (there's the problem) tasked with emitting JSON to be used with Knockout.js to render sets of dependent list items. I have just started working with Knockout, so this is likely something obvious that I am missing.
Here is the markup:
<select data-bind="options:data,
optionsText:'leadTime',
value:leadTimes">
</select>
<!--ko with: leadTimes -->
<select data-bind="options:colors,
optionsText:'name',
optionsValue:'key',
value:$root.colorsByLeadTime">
</select>
<!--/ko-->
Here is the test data and code:
var data = [
{
key:"1",
leadTime:"Standard",
colors:[
{ key:"11", name:"Red" },
{ key:"12", name:"Orange" },
{ key:"13", name:"Yellow" }
]
},
{
key:"2",
leadTime:"Quick",
colors:[
{ key:"21", name:"Black" },
{ key:"22", name:"White" }
]
}
]
var dataViewModel = ko.mapping.fromJS(data);
var mainViewModel = {
data:dataViewModel,
leadTimes:ko.observable(),
colorsByLeadTime:ko.observable()
}
ko.applyBindings(mainViewModel);
As this stands, it correctly populates the value attribute of the second select list. However, if I add optionsValue:'key' to the first select list then the value attribute for that is set correctly but the second select list renders as an empty list.
All I need is for the value attribute of the option tag to be set to the key value provided in the data, regardless of where the select list is in the set of dependent lists. I've looked at many articles and the docs, but this particular scenario (which I would think is very common) is eluding me.
Here is a jsfiddle with the data, JS, and markup as given above: http://jsfiddle.net/tnagle/Lyxjt11y/
To really see the issue, you can add the following code after the initialization of mainViewModel.
mainViewModel.leadTimes.subscribe(function(newValue) {
console.log(newValue);
debugger;
});
Before adding the optionsValue:'key', line above will log the following output.
Object {key: function, leadTime: function, colors: function}
But after adding optionsValue:'key', it log the following output.
"1"
or
"2"
The reason it failed was because when you assign optionsValue: 'key' to the first select list, leadTimes property of your mainViewModel which before will contain an object that has property color, now will be set to a string object. Then the select list just failed to find color property from leadTimes that has changed to a string object.
One of the way to make it work is by changing to this:
var data = [
{
key:"1",
leadTime:"Standard",
colors:[
{ key:"11", name:"Red" },
{ key:"12", name:"Orange" },
{ key:"13", name:"Yellow" }
]
},
{
key:"2",
leadTime:"Quick",
colors:[
{ key:"21", name:"Black" },
{ key:"22", name:"White" }
]
}
]
var dataViewModel = ko.mapping.fromJS(data);
var mainViewModel = new function (){
var self = this;
self.data = dataViewModel;
self.leadTimes = ko.observable();
self.selectedKey = ko.observable();
self.selectedKey.subscribe(function(selectedKey){
self.selectedData(ko.utils.arrayFirst(self.data(), function(item) {
return item.key() == selectedKey;
}));
}, self);
self.colorsByLeadTime = ko.observable();
self.selectedData = ko.observable();
}
ko.applyBindings(mainViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<select data-bind="options:data,
optionsText:'leadTime',
optionsValue:'key',
value:selectedKey">
</select>
<!--ko with: selectedData -->
<select data-bind="options:colors,
optionsText:'name',
optionsValue:'key',
value:$root.colorsByLeadTime">
</select>
<!--/ko-->

Knockout computed executed on page load

Basically i have a drop down on selecting which there will be another drop down loaded. I have a computed variable depending on first drop down selected value(I know it can be subscribed,but still). But the computed is executed on page load which i dont want due to an AJAX call inside. 'What is the reason for the execution on page load and how to avoid that?
HTML:
<div>
<select id="selectmenu1" data-bind="options: departments,
optionsValue: 'id',
optionsText: 'name',
optionsCaption: 'Choose...',value: selectedDept">
</select>
<select id="selectmenu1" data-bind="options: contacts,
optionsValue: 'id',
optionsText: 'name',
optionsCaption: 'Choose...'">
</select>
</div>
And JS
// Here's my data model
var ViewModel = function(first, last) {
var self = this;
var deptArray = [];
var deptObj = {
id: "8888",
name: "Electrical"
};
deptArray[0] = deptObj;
deptObj = {
id: "9999",
name: "Admin"
};
deptArray[1] = deptObj;
self.departments = ko.observableArray(deptArray);
self.selectedDept = ko.observable();
self.contacts = ko.observableArray();
self.contactsRetrieve = ko.computed(function() {
var deptId = self.selectedDept();
console.log("entered");
$.ajax({
url: '/echo/js',
complete: function(response) {
console.log("success");
var contactArray = [];
var contactObj = {};
if (deptId == '8888') {
contactObj.id = '1234';
contactObj.name = 'Vivek';
} else if (deptId == '9999') {
contactObj.id = '5678';
contactObj.name = 'Sree';
}
contactArray[0] = contactObj;
self.contacts(contactArray);
}
});
console.log("exited");
});
};
ko.applyBindings(new ViewModel());
https://jsfiddle.net/jtjozkax/37/
if(!self.selectedDept()){return}
Using this if statement to cancel functionality within the computed if there is no selected option.
https://jsfiddle.net/jtjozkax/38/
As far as I know, it is not the page load itself that causes this behavior, but the fact that computed observables rely on other observables, in your case, self.selectedDept. Knockout discovers which other observables the computed relies on, and it is actually the change of value of selectedDept what causes the computed to be recomputed.
You cannot avoid this behavior, but you can avoid the execution of the AJAX call by adding a guarding condition (read: if statement). I assume your goal is to prevent the AJAX-call if nothing is selected in the dropdown, and, afterall, this is the most straightforward way to accomplish just that.
There is no other way around it, simply because if you think about it, the whole purpose of a computed is to reevalue itself whenever any other observable it depends on changes, without manual intervention.

binding multi dropdown list in knockout.js

I have a multi dropdown list and I need to do the following:
1. Make sure that when selecting value in one dropdown list it won't appear in the others (couldn't find a proper solution here).
2. When selecting the value "Text" a text field (<input>) will apear instead of the Yes/no dropdown.
3. "Choose option" will appear only for the first row (still working on it).
4. Make sure that if "Text" is selected, it always will be on the top (still working on it).
JSFiddle
HTML:
<div class='liveExample'>
<table width='100%'>
<tbody data-bind='foreach: lines'>
<tr>
<td>
Choose option:
</td>
<td>
<select data-bind='options: filters, optionsText: "name", value: filterValue'> </select>
</td>
<td data-bind="with: filterValue">
<select data-bind='options: filterValues, optionsText: "name", value: "name"'> </select>
</td>
<td>
<button href='#' data-bind='click: $parent.removeFilter'>Remove</button>
</td>
</tr>
</tbody>
</table>
<button data-bind='click: addFilter'>Add Choice</button>
JAVASCRIPT:
var CartLine = function() {
var self = this;
self.filter = ko.observable();
self.filterValue = ko.observable();
// Whenever the filter changes, reset the value selection
self.filter.subscribe(function() {
self.filterValue(undefined);
});
};
var Cart = function() {
// Stores an array of filters
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
// Operations
self.addFilter = function() { self.lines.push(new CartLine()) };
self.removeFilter = function(line) { self.lines.remove(line) };
};
ko.applyBindings(new Cart());
I will appeaciate your assist here! Mainly for the first problem.
Thanks!
Mike
If you want to limit the options based on the options that are already selected in the UI, you'll need to make sure every cartLine gets its own array of filters. Let's pass it in the constructor like so:
var CartLine = function(availableFilters) {
var self = this;
self.availableFilters = availableFilters;
// Other code
// ...
};
You'll have to use this new viewmodel property instead of your global filters array:
<td>
<select data-bind='options: availableFilters,
optionsText: "name",
value: filterValue'> </select>
</td>
Now, we'll have to find out which filters are still available when creating a new cartLine instance. Cart manages all the lines, and has an addFilter function.
self.addFilter = function() {
var availableFilters = filters.filter(function(filter) {
return !self.lines().some(function(cartLine) {
var currentFilterValue = cartLine.filterValue();
return currentFilterValue &&
currentFilterValue.name === filter.name;
});
});
self.lines.push(new CartLine(availableFilters))
};
The new CartLine instance gets only the filter that aren't yet used in any other line. (Note: if you want to use Array.prototype.some in older browsers, you might need a polyfill)
The only thing that remains is more of an UX decision than a "coding decision": do you want users to be able to change previous "Choices" after having added a new one? If this is the case, you'll need to create computed availableFilters arrays rather than ordinary ones.
Here's a forked fiddle that contains the code I posted above: http://jsfiddle.net/ztwcqL69/ Note that you can create doubled choices, because choices remain editable after adding new ones. If you comment what the desired behavior would be, I can help you figure out how to do so. This might require some more drastic changes... The solution I provided is more of a pointer in the right direction.
Edit: I felt bad for not offering a final solution, so here's another approach:
If you want to update the availableFilters retrospectively, you can do so like this:
CartLines get a reference to their siblings (the other cart lines) and create a subscription to any changes via a ko.computed that uses siblings and their filterValue:
var CartLine = function(siblings) {
var self = this;
self.availableFilters = ko.computed(function() {
return filters.filter(function(filter) {
return !siblings()
.filter(function(cartLine) { return cartLine !== self })
.some(function(cartLine) {
var currentFilterValue = cartLine.filterValue();
return currentFilterValue &&
currentFilterValue.name === filter.name;
});
});
});
// Other code...
};
Create new cart lines like so: self.lines.push(new CartLine(self.lines)). Initiate with an empty array and push the first CartLine afterwards by using addFilter.
Concerning point 2: You can create a computed observable that sorts based on filterValue:
self.sortedLines = ko.computed(function() {
return self.lines().sort(function(lineA, lineB) {
if (lineA.filterValue() && lineA.filterValue().name === "Text") return -1;
if (lineB.filterValue() && lineB.filterValue().name === "Text") return 1;
return 0;
});
});
Point 3: Move it outside the foreach.
Point 4: Use an if binding:
<td data-bind="with: filterValue">
<!-- ko if: name === "Text" -->
<input type="text">
<!-- /ko -->
<!-- ko ifnot: name === "Text" -->
<select data-bind='options: filterValues, optionsText: "name", value: "name"'> </select>
<!-- /ko -->
<td>
Updated fiddle that contains this code: http://jsfiddle.net/z22m1798/

Knockout.js - Creating a reusable cascading select

Is it possible to create a reusable cascading combo box from a dictionary object using KO ?
For example, this data
{'A' : { 'A1':11, 'A2':12} ,
'B' : { 'B1':21, 'B2':22, 'B3':33},
'C' : { 'C1':31}}
would produce two cascading boxes, the first with the options 'A,B,C'. the second would update according to the selection. The dict might change in height but the tree will always be balanced.
Is it possible to create the elements from within a custom binding ? can a custom binding contain other custom bindings and subscribe to them ? is custom binding even the right approach here ?
I would appreciate some guidance.
Basically this is what I have done
Create a predefined structure /class which knows if it has list of
values or just a single value.
On the view side show the dropdown if its list else just show the text.
On the root vm nest the structure created in step one and create the dict.
Here is the VM
var optionVM = function (name,isList, v) {
var self = this;
self.name=ko.observable(name);
if (isList) self.values = ko.observableArray(v);
else self.value = ko.observable(v);
self.isList = ko.observable(isList);
self.selected = ko.observable();
}
var vm = function () {
var self = this;
var a1Vm = new optionVM('A1',true, [new optionVM('A11',false,111), new optionVM('A12',false,122)]);
var aVm = new optionVM('A',true, [new optionVM('A2',false,'21'), a1Vm]);
var d = new optionVM('Root',true, [aVm, new optionVM('B',false,'B1'),new optionVM('C',false,'C1')]);
self.dict = ko.observable(d);
}
ko.applyBindings(new vm());
Here is the view
<select data-bind='options:dict().values,optionsText:"name",value:dict().selected'>
</select>
<div data-bind="template: {name: 'template-detail', data: dict().selected}"></div>
<script type="text/html" id='template-detail'>
<!-- ko if:$data.isList -->
<span> List:</span>
<select data-bind='options:values,optionsText:"name",value:selected'>
</select>
<div data-bind="template: {name: 'template-detail', data: selected}"></div>
<!-- /ko -->
<!-- ko ifnot:$data.isList -->
Value:<span data-bind="text:value"></span>
<!-- /ko -->
</script>
And here is the jsFiddle
Improvements:
You can use isArray to identify if its list in the optionVM.
Some of the observables can be replaced with simple values if they are not going to change (e.g:name)

Update related properties in response to observable change

Update
My original post is pretty long - here's the tl;dr version:
How do you update all properties of a knockout model after a single property has changed? The update function must reference an observableArray in the viewModel.
-- More details --
I'm using KnockoutJS. I have a Zoo and a Tapir model and three observables in the viewmodel - zoos, tapirCatalog and currentTapir. The tapirCatalog is populated from the server and the currentTapir holds the value of whichever tapir is being edited at the time.
Here's what I'm trying to accomplish: A user has added a tapir from a list of tapirs to his/her zoo. When viewing the zoo, the user can edit a tapir and replace it with another. To do this a popup window is shown with a select form populated by tapir names and a span showing the currently selected GoofinessLevel.
So, when the select element changes this changes the TapirId in currentTapir. I want that to trigger something that changes the currentTapir's Name and GoofinessLevel.
I tried subscribing to currentTapir().GoofinessLevel but cannot get it to trigger:
function Zoo(data) {
this.ZooId = ko.observable(data.ZooId);
this.Tapirs = ko.observableArray(data.Tapirs);
}
function Tapir(data) {
this.TapirId = ko.observable(data.TapirId);
this.Name = ko.observable(data.Name);
this.GoofinessLevel = ko.observable(data.Name);
}
function ViewModel() {
var self = this;
// Initializer, because I get an UncaughtType error because TapirId is undefined when attempting to subscribe to it
var tapirInitializer = { TapirId: 0, Name: "Template", GoofinessLevel: 0 }
self.zoos = ko.observableArray([]);
self.tapirCatalog = ko.observableArray([]);
self.currentTapir = ko.observable(new Tapir(tapirInitializer));
self.currentTapir().TapirId.subscribe(function (newValue) {
console.log("TapirId changed to: " + newValue);
}); // This does not show in console when select element is changed
};
Oddly enough, when I subscribe to the Goofiness level inside the Tapir model I get the trigger:
function Tapir(data) {
var self = this;
self.TapirId = ko.observable(data.TapirId);
self.Name = ko.observable(data.Name);
self.GoofinessLevel = ko.observable(data.Name);
self.TapirId.subscribe(function (newId) {
console.log("new TapirId from internal: " + newId);
}); // This shows up in the console when select element is changed
}
I suspect that this is a pretty common scenario for people using KO but I haven't be able to find anything. And I've searched for a while now (it's possible that I may not have the correct vocabulary to search with?). I did find this solution, but he references the viewmodel from the model itself -- which seems like back coding since I would think the Tapir should not have any knowledge of the Zoo: http://jsfiddle.net/rniemeyer/QREf3/
** Update **
Here's the code for my select element (the parent div has data-bind="with: currentTapir":
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: TapirId">
</select>
It sounds like what you need to do is bind the select to an observable instead of the Id
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: currentTapir">
</select>

Categories

Resources