A pattern to be designed using template binding of knockoutjs - javascript

We have a situation as mentioned below:
There is a set of data for a search panel, it's called in several pages with different types of components and placement of it. There can be combo boxes, radio buttons, input boxes and buttons.
Knockout has a feature of template binding in which we can have the flexibility to show numerous panels on condition using a template in the html mapped to MOdel.
Below is the code and pattern:
HTML:
<div id="content-wrapper">
<div class="spacer"></div>
<div>
<table class="data-table">
<thead>
<tr>
<th colspan="4"> Search </th>
</tr>
</thead>
<tbody data-bind="foreach: preSearchData" >
<tr>
<!-- ko template: { name: 'label_' + templateName()} -->
<!-- /ko -->
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/html" id="label_Combo">
<td>It is a Combo </td>
</script>
<script type="text/html" id="label_Number">
<td>
It is a Number
</td>
</script>
MODEL:
Models.Components = function(data) {
var self = this;
self.number = data.number;
self.labelCd = data.labelCd;
self.xmlTag = data.xmlTag;
self.Type = new Cobalt.Models.Type(data.Type);
};
Models.Type = function(data) {
var self = this;
self.component = data.component;
self.records = data.records;
self.minLength = data.minLength;
self.maxLength = data.maxLength;
self.defaultValue = data.defaultValue;
self.targetAction = data.targetAction;
};
Models.ComponentType = function (paymentTypeCode, data, actionId) {
var ret;
self.templateName(data.component);
if (!data || (actionId === Cobalt.Constant.Dashboard.copyProfile))
data = {};
if (paymentTypeCode == Cobalt.Constant.Dashboard.creditCard)
ret = new Cobalt.Models.CreditCardPaymentType(data.cardHolderName, data.cardNumber, data.cardExpireDate);
else if (paymentTypeCode == Cobalt.Constant.Dashboard.dd)
ret = new Cobalt.Models.DDPaymentType(data.pinNumber);
else if (Cobalt.Utilities.startsWith(paymentTypeCode, Cobalt.Constant.Dashboard.yahooWallet)) {
if (!data && paymentTypeCode.indexOf('~') > -1) {
data.payCode = paymentTypeCode.substr(paymentTypeCode.indexOf('~') + 1, paymentTypeCode.lastIndexOf('~'));
data.billingAgentId = paymentTypeCode.substr(paymentTypeCode.lastIndexOf('~') + 1);
}
ret = new Cobalt.Models.WalletPaymentType(data.payCode, data.billingAgentId);
}
else if (paymentTypeCode == Cobalt.Constant.Dashboard.ajl) {
ret = new Cobalt.Models.DDPaymentType(data.pinNumber);
}
else
ret = data || {};
return ret;
};
Models.POCModel = function () {
var self = this;
self.templateName = ko.observable();
self.preSearchData = ko.observableArray([]);
self.getResultData = function () {
var data = Cobalt.Data.getResultData();
var componentList = data.componentList;
self.preSearchData(componentList);
};
};
Above code gives me a error saying:
Ajax error: parsererror ( Error: Unable to parse bindings. Message: ReferenceError: templateName is not defined; Bindings value: template:
{ name: 'label_' + templateName()} ) cobalt.init.js:66

This is not a direct answer to your question, but it shows an alternate way of doing this using the ViewModel type to find the view (Template)
http://jsfiddle.net/nmLsL/2
Each type of editor is a ViewModel
MyApp.Editors.BoolViewModel = function(data) {
this.checked = data;
};
MyApp.Editors.BoolViewModel.can = function(data) {
return typeof data === "boolean";
};
And it has a can function that determins if it can edit the value
I then usea library called Knockout.BindingConventions to find the template connected to the ViewModel
https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki/Template-convention

Your foreach binding creates a child binding context, which doesn't include templateName since that's part of the parent. Replace it with
<!-- ko template: { name: 'label_' + $parent.templateName()} -->

Related

go back to before directive was used in angularJS

I'm working on a project at the moment using angular JS.
I've used a directive to switch from advanced search so that the results can be viewed on its own page. basically when submit is clicked, the advanced search is hidden and only results table can be seen. so now, once on results table, I want to be able to go back to that advanced search to the point before I hit that submit button, the data is still there, I have just reversed the directive in a way. any suggestions would be greatly appreciated, this is all fairly new to me.
thanks! (please note, my search controller uses TypeScript)
this is being called just under the submit button on the search_partial.html
<div class="submit">
<button class="btn btn-primary" type="button" name="Submit" ng-click="vm.validateForm()" ng-disabled="!(!!vm.hospitalNumberInput || !!vm.nhsNumberInput || !!vm.fullNameInput || !!vm.sexInput || vm.yearOfBirthInput || !!vm.streetInput || !!vm.cityInput
|| !!vm.postCodeInput || !!vm.chosenCountry)">Search</button>
Clear all
</div>
</form>
<section>
<div id="searchDirective" search-results patients="vm.results" class="ng-hide"></div>
</section>
and I have a directives file called search.results.directive.js
(function () {
angular
.module('app.search.results')
.directive('searchResults', function() {
return {
restrict: 'AE',
templateUrl: 'app/search/Partials/result_partial.html',
scope: {
patients: '='
}
};
});
})();
so what I'm trying to do now that I can see the results-partial.html on the screen in front of me, I want to be able to click a back button on there to take me back to the search-partial.html at the point before the user clicked that submit button so that the data in the boxes can be altered if needs be or more search data added. (at the moment I have a back href going to the home url, it works for now, but that's what im hoping to replace).
results-partial.html:
<main class="container">
<!-- RESULT -->
<section class="result-display">
<form>
<div class="searchresults content table-responsive">
<h2>Search Criteria: </h2>
<h2> Search Results: {{patients.length}} patients found</h2>
<table class="table resultstable table-striped">
<thead>
<tr class="theading">
<th>Hospital number</th>
<th>NHS Number</th>
<th>Full Name</th>
<th>DOB</th>
<th>Sex</th>
</tr>
</thead>
<!--repeated simply for style insight-->
<tbody>
<tr ng-repeat="patient in patients">
<td>{{patient.resource.hospitalNumber}}</td>
<td>{{patient.resource.nhsNumber}}</td>
<td>{{patient.resource.nameString}}</td>
<td>{{patient.resource.birthDate}}</td>
<td>{{patient.resource.gender.toUpperCase()}}</td>
</tr>
</tbody>
</table>
</div>
<a href style="float: right; font-size:120%;" onclick="location.href='http://localhost:3000/';"><i class="close"></i><u>Back to Search</u></a>
</form>
</section>
</main>
If I understand the question right, you want to preserve the values in the input.
You can use a factory or value to store the data.
myApp.factory('DataHolder', function (){
return data;
});
// Or, with value
myApp.value('DataHolder', data);
And in your controller you can access that data anywhere.
myApp.controller('Ctrl', function ($scope, DataHolder){
$scope.data = DataHolder;
});
So when you come back to the back state, if you have data stored you can get it back to show it.
fixed it. managed to get it working my changing the flag to false with "returnToSearch()" function at the bottom.
createDisplayParams(): void {
// add in search params to display params
var paramTypes: string[] = [];
for (var i: number = 0; i < this.searchParams.length; ++i) {
var objectIndex: number = paramTypes.indexOf(this.searchParams[i].ParamName);
if (objectIndex === -1) {
// if param name dosen't exist, add it to the paramTypes
paramTypes.push(this.searchParams[i].ParamName);
}
}
for (var j: number = 0; j < paramTypes.length; ++j) {
var valueParams: core.ISearchParam[] = [];
valueParams =_.filter(this.searchParams, searchParam => { //lodash
return searchParam.ParamName == paramTypes[j];
});
var valueStrings: string[] = [];
valueParams.forEach(v => valueStrings.push(v.ParamValue));
this.displayParams.push({ paramType: paramTypes[j], paramValue: valueStrings.join(", ") });
}
}
obtainPatientInformation(): void {
this.createSearchParams();
if (this.searchParams.length > 0) {
var rawResults: angular.IPromise<core.IPatient> = this.searchDataService.performAdvancedSearch(this.searchParams);
var searchControllerInstance: SearchController = this;
this.createDisplayParams();
rawResults.then(
function success(response: any): void {
if (response.data.entry && response.data.entry.length > 0) {
searchControllerInstance.noResults = false;
searchControllerInstance.results = response.data.entry;
for (var index: number = 0; index < searchControllerInstance.results.length; index++) {
var patient: core.IEntry = searchControllerInstance.results[index];
patient.resource.nameString = '';
if (patient.resource.name) {
var familyNameArray: string[] = patient.resource.name[0].family;
for (var familyIndex: number = 0; familyIndex < familyNameArray.length; familyIndex++) {
var familyName: string = familyNameArray[familyIndex];
patient.resource.nameString = patient.resource.nameString + ' ' + familyName.toUpperCase() + ',';
}
var givenNameArray: string[] = patient.resource.name[0].given;
for (var givenIndex: number = 0; givenIndex < givenNameArray.length; givenIndex++) {
var givenName: string = givenNameArray[givenIndex];
patient.resource.nameString = patient.resource.nameString + ' ' + givenName;
}
}
var identifiers: core.IIdentifier[] = patient.resource.identifier;
for (var indentifierIndex: number = 0; indentifierIndex < identifiers.length; indentifierIndex++) {
var identifier: core.IIdentifier = identifiers[indentifierIndex];
if (identifier.system) {
if (identifier.system === 'nhsNumber') {
patient.resource.nhsNumber = identifier.value;
}
if (identifier.system === 'hospitalNumber') {
patient.resource.hospitalNumber = identifier.value;
}
}
}
}
} else {
searchControllerInstance.noResults = true;
searchControllerInstance.results = null;
}
});
}
this.searchClicked = true;
this.checkSearch();
}
checkSearch(): void {
var resultSectionElements: angular.IAugmentedJQuery = angular.element('[id*="resultSection"]');
var advanceSearchSectionElements: angular.IAugmentedJQuery = angular.element('[id*="advanceSearchSection"]');
if (this.searchClicked) {
resultSectionElements.removeClass('ng-hide');
advanceSearchSectionElements.removeClass('ng-show');
advanceSearchSectionElements.addClass('ng-hide');
} else {
resultSectionElements.addClass('ng-hide');
advanceSearchSectionElements.removeClass('ng-hide');
advanceSearchSectionElements.addClass('ng-show');
}
}
returnToSearch(): void {
this.searchClicked = false;
this.searchParams.splice(0,this.searchParams.length);
this.displayParams.splice(0,this.displayParams.length);
this.checkSearch();
}

Access jQuery Object from inside a custom binding handler

I am trying to access a jQuery Object, which happens to be an input text box to do some validations and adding date picker but unfortunately I am unable to do so.
I am working with KnockoutJS.
I wanted to access the 'input' and call datepicker() on it if 'Datatype' happens to be a 'Date' or a 'Datetime'. But whenever I try to search using .closest('td').next('td').html(), I get a null (from inside the custom bind). Trying this so that I can call the datetimepicker constructor on the input based on the datatype 'td'.
Below is the fiddle that I am trying to work with
JsFiddle: http://jsfiddle.net/sourabhtewari/nkkt88v2/2/
var format = function (str, col) {
col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);
return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
if (m == "{{") {
return "{";
}
if (m == "}}") {
return "}";
}
return col[n];
});
};
var data = ko.observableArray([{
paramKey: ko.observable('keyName'),
paramValue: ko.observable('Test1'),
dataType: ko.observable('Date')
}]);
var ParamConstr = function (key, value, dataType) {
return {
ParamKey: ko.observable(key),
ParamValue: ko.observable(value),
DataType: ko.observable(dataType)
};
};
var my = my || {};
function Generator() { };
Generator.prototype.rand = Math.floor(Math.random() * 26) + Date.now();
Generator.prototype.getId = function () {
return this.rand++;
};
var idGen = new Generator();
//var ParamData = ko.observableArray([]);
my.viewModel = {
ParamData : ko.observableArray([]),
addParam: function () {
this.ParamData.push(new ParamConstr("$$" + "key1", "value1","Date"));
}};
ko.bindingHandlers.hidden = {
update: function (element, valueAccessor) {
ko.bindingHandlers.visible.update(element, function () { return !ko.utils.unwrapObservable(valueAccessor()); });
}
};
ko.bindingHandlers.clickToEdit = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
var observable = valueAccessor(),
link = document.createElement("a"),
input = document.createElement("input");
var id = idGen.getId();
input.setAttribute("id", id);
element.appendChild(link);
element.appendChild(input);
console.log(document.getElementById(id).id);
var dataType = $(format("#{0}", id)).parent().next('td').html();
//.parent().next().html();
//.closest('td').next('td').html().toString();
console.log(dataType);
switch ($(format("#{0}", id)).parent().next('td').html()) {
case "Datetime":
$(format("#{0}", id)).datetimepicker();
break;
case "Date":
$(format("#{0}", id)).datetimepicker({
timepicker: false,
format: 'Y/m/d'
});
break;
}
observable.editing = ko.observable(false);
ko.applyBindingsToNode(link, {
text: observable,
hidden: observable.editing,
click: observable.editing.bind(null, true)
});
ko.applyBindingsToNode(input, {
value: observable,
visible: observable.editing,
hasfocus: observable.editing,
event: {
keyup: function (data, event) {
//if user hits enter, set editing to false, which makes field lose focus
if (event.keyCode === 13) {
input.blur();
observable.editing(false);
return false;
}
//if user hits escape, push the current observable value back to the field, then set editing to false
else if (event.keyCode === 27) {
observable.valueHasMutated();
observable.editing(false);
return false;
}
}
}
});
}
};
ko.applyBindings(my.viewModel);
html:
<div>
<button id="InputSubmitBtn" type="submit" class="btn btn-custom" data-bind="click: addParam"><span class="glyphicon glyphicon-plus-sign"></span> Add</button>
</div>
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Data type</th>
</tr>
</thead>
<tbody data-bind="foreach: ParamData">
<tr>
<td data-bind="text: ParamKey" style="width: 20%"></td>
<td data-bind="clickToEdit: ParamValue" data-text="" style="width: 20%"></td>
<td data-bind="text: DataType" style="width: 20%"></td>
</tr>
</tbody>
</table>
Any help as to how I can fix this would be great!
So it seems you got an answer from G_S.
If anyone is wondering what was the right selector, var dataType = $(element).next().text(); does the job perfectly. You couldn't access any data because at the time of the call, it wasn't there yet. You could try var dataType = $(element).prev().text(); and see that you can retrieve $$key1.
Fiddle
Anyway, as you got answered, I didn't dig further on how to resolve this, have a good day :)

Create grid with knockoutjs

Let's say we have an observable array of N+1 elements. What i would like to achive is to build 3 by X grid with buttons from these elements. Like phone keypad or something like this.
What i have done so far is created a table with foreach and if in it:
<table>
<tbody data-bind="foreach: tableList">
<!-- ko if: isEof($index()) -->
<tr>
<!-- /ko -->
<td><button data-bind="text: name"></button></td>
<!-- ko if: isEof($index()) -->
</tr>
<!-- /ko -->
</tbody>
</table>
isEof() function should determine by list index wether we have already 3 elements rendered. If yes, then it will render tags. Also if index is 0, then it also renders elements.
This is the code of the function:
function TableItem(data){
this.id=ko.observable(data.id);
this.name=ko.observable(data.name);
this.isEof = function(index){
if(index ==0){
return true;
}else{
if((index+3) % 3 === 0){
return true;
}else{
return false;
}
}
}
}
But i'm facing two problems with this setup.
1) With these if blocks enabled, button name binding does not work. When i remove ko if blocks, it will be rendered correctly.
2) ko if statements does not seem to work correctly. It will render out only those lines, where is also allowed to render.
I've made JSFiddle sample of my solution: http://jsfiddle.net/kpihus/3Lw7xjae/2/
I would create a ko.computed that converts your list of table items into an array of arrays:
var TableItem = function TableItem(data) {
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
};
var Vm = function Vm() {
this.tableItems = ko.observableArray([]);
this.columnCount = ko.observable(3);
this.columns = ko.computed(function() {
var columns = [],
itemCount = this.tableItems().length,
begin = 0;
// we use begin + 1 to compare to length, because slice
// uses zero-based index parameters
while (begin + 1 < itemCount) {
columns.push( this.tableItems.slice(begin, begin + this.columnCount()) );
begin += this.columnCount();
}
return columns;
// don't forget to set `this` inside the computed to our Vm
}, this);
};
vm = new Vm();
ko.applyBindings(vm);
for (var i = 1; i < 15; i++) {
vm.tableItems.push(new TableItem({
id: i,
name: "name: " + i
}));
}
This way, you can display your table by nesting two foreach bindings:
<table>
<tbody data-bind="foreach: { data: columns, as: 'column' }">
<tr data-bind="foreach: column">
<td>
<button data-bind="text: name">A</button>
</td>
</tr>
</tbody>
</table>
JSFiddle
If you haven't worked with ko.computed before, they track whatever observables are accessed inside of them — in this case, this.tableItems and this.columnCount —, and whenever one of them changes, they run again and produce a new result.
this.columns takes our array of table items
[TableItem, TableItem, TableItem, TableItem, TableItem, TableItem]
and groups them by this.columnCount into
[[TableItem, TableItem, TableItem], [TableItem, TableItem, TableItem]]
We can achieve this by simply passing $root which will have tableList and do the looping in simple way .
View Model:
function TableItem(data) {
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.pickarray = ko.observableArray();
self.isEof = function (index, root) {
if (index === 0) {
self.pickarray(root.tableList().slice(index, index + 3));
return true;
} else if ((index + 3) % 3 === 0) {
self.pickarray(root.tableList().slice(index, index + 3));
return true;
} else {
return false;
}
}
}
var vm = function () {
this.tableList = ko.observableArray();
for (var i = 1; i < 15; i++) {
this.tableList.push(new TableItem({
id: i,
name: "name: " + i
}));
}
}
ko.applyBindings(new vm());
View :
<table data-bind="foreach:tableList">
<tr data-bind="if:isEof($index(),$root)">
<!-- ko foreach: pickarray -->
<td>
<button data-bind="text: id"></button>
</td>
<!-- /ko -->
</tr>
</table>
Trick here is very simple we just need to conditionally fill pickarray which does the job for us .
Working Fiddle here

How can I toggle the display of a textarea via a button using knockout with the foreach binding?

I am new to knockout. For my problem, I am trying to make it so that for each project, there is a button and textarea. The textarea will be hidden upon page load. If I click the button, it will show the textarea (toggle). Currently, if I click the button, ALL textareas on the page will show, rather than just the corresponding textarea.
I'm hoping the fix for this isn't too dramatic and involving a complete reworking of my code as by some magic, every other functionality has been working thus far. I added the {attr id: guid} (guid is a unique identifier of a project retrieved from the database) statement in an attempt to establish a unique ID so that the right controls were triggered...although that did not work.
Sorry I do not have a working jfiddle to show the issue... I tried to create one but it does not demonstrate the issue.
JS:
//if a cookie exists, extract the data and bind the page with cookie data
if (getCookie('filterCookie')) {
filterCookie = getCookie('filterCookie');
var cookieArray = filterCookie.split(",");
console.log(cookieArray);
$(function () {
var checkboxes = new Array();
for (var i = 0; i < cookieArray.length; i++) {
console.log(i + cookieArray[i]);
checkboxes.push(getCheckboxByValue(cookieArray[i]));
//checkboxes.push(document.querySelectorAll('input[value="' + cookieArray[i] + '"]'));
console.log(checkboxes);
checkboxes[i].checked = true;
}
})
filterCookie = getCookie('filterResultsCookie');
cookieArray = filterCookie.split(",");
filterCookieObj = {};
filterCookieObj.action = "updateProjects";
filterCookieObj.list = cookieArray;
$.ajax("/api/project/", {
type: "POST",
data: JSON.stringify(filterCookieObj)
}).done(function (response) {
proj = response;
ko.cleanNode(c2[0]);
c2.html(original);
ko.applyBindings(new ProjectViewModel(proj), c2[0]);
});
}
//if the cookie doesn't exist, just bind the page
else {
$.ajax("/api/project/", {
type: "POST",
data: JSON.stringify({
action: "getProjects"
})
}).done(function (response) {
proj = response;
ko.cleanNode(c2[0]);
c2.html(original);
ko.applyBindings(new ProjectViewModel(proj), c2[0]);
});
}
View Model:
function ProjectViewModel(proj) {
//console.log(proj);
var self = this;
self.projects = ko.observableArray(proj);
self.show = ko.observable(false);
self.toggleTextArea = function () {
self.show(!self.show());
};
};
HTML:
<!-- ko foreach: projects -->
<div id="eachOppyProject" style="border-bottom: 1px solid #eee;">
<table>
<tbody>
<tr>
<td><a data-bind="attr: { href: '/tools/oppy/' + guid }" style="font-size: 25px;"><span class="link" data-bind=" value: guid, text: name"></span></a></td>
</tr>
<tr data-bind="text: projectDescription"></tr>
<%-- <tr data-bind="text: guid"></tr>--%>
</tbody>
</table>
<span class="forminputtitle">Have you done project this before?</span> <input type="button" value="Yes" data-bind="click: $parent.toggleTextArea" class="btnOppy"/>
<textarea placeholder="Tell us a little of what you've done." data-bind="visible: $parent.show, attr: {'id': guid }" class="form-control newSessionAnalyst" style="height:75px; " /><br />
<span> <input type="checkbox" name="oppyDoProjectAgain" style="padding-top:10px; padding-right:20px;">I'm thinking about doing this again. </span>
<br />
</div><br />
<!-- /ko -->
Spencer:
function ProjectViewModel(proj) {
//console.log(proj);
var self = this;
self.projects = ko.observableArray(proj);
self.projects().forEach(function() { //also tried proj.forEach(function())
self.projects().showComments = ko.observable(false);
self.projects().toggleComments = function () {
self.showComments(!self.showComments());
};
})
};
It's weird that
data-bind="visible: show"
doesn't provide any binding error because context of binding inside ko foreach: project is project not the ProjectViewModel.
Anyway, this solution should solve your problem:
function ViewModel() {
var self = this;
var wrappedProjects = proj.map(function(p) {
return new Project(p);
});
self.projects = ko.observableArray(wrappedProjects);
}
function Project(proj) {
var self = proj;
self.show = ko.observable(false);
self.toggleTextArea = function () {
self.show(!self.show());
}
return self;
}
The problem is that the show observable needs to be defined in the projects array. Currently all the textareas are looking at the same observable. This means you'll have to move the function showTextArea into the projects array as well.
Also you may want to consider renaming your function or getting rid of it entirely. Function names which imply they drive a change directly to the view fly in the face of the MVVM pattern. I'd recommend a name like "toggleComments" as it doesn't reference a view control.
EDIT:
As an example:
function ProjectViewModel(proj) {
//console.log(proj);
var self = this;
self.projects = ko.observableArray(proj);
foreach(var project in self.projects()) {
project.showComments = ko.observable(false);
project.toggleComments = function () {
self.showComments(!self.showComments());
};
}
};
There is probably a much cleaner way to implement this in your project I just wanted to demonstrate my meaning without making a ton of changes to the code you provided.

KnockoutJS Select on model

I'm trying to bind a 1-many mapping using KnockoutJS, where 1 zip code can have many 'agents'. I have the following classes:
function CaseAssignmentZipCode(zipcode, agent) {
var self = this;
self.zipcode = ko.observable(zipcode);
self.agent = ko.observable(agent);
}
function Agent(id, name) {
var self = this;
self.id = id;
self.name = name;
}
function ZipcodeAgentsViewModel() {
var self = this;
self.caseAssignmentZipCodes = ko.observableArray([]);
self.agents = ko.observableArray([]);
jdata = $.parseJSON($('#Agents').val());
var mappedAgents = $.map(jdata, function (a) { return new Agent(a.Id, a.Name) });
self.agents(mappedAgents);
var dictAgents = {};
$.each(mappedAgents, function (index, element) {
dictAgents[element.id] = element;
});
var jdata = $.parseJSON($('#CaseAssignmentZipCodes').val());
var mappedZipcodeAgents = $.map(jdata, function (za) { return new CaseAssignmentZipCode(za.ZipCode, dictAgents[za.UserId], false) });
self.caseAssignmentZipCodes(mappedZipcodeAgents);
}
var vm = new ZipcodeAgentsViewModel()
ko.applyBindings(vm);
My bindings look like this:
<table>
<thead><tr><th>Zipcode Agents</th></tr></thead>
<tbody data-bind="foreach: caseAssignmentZipCodes">
<tr>
<td><input data-bind="value: zipcode"></td>
<td><select data-bind="options: $root.agents, value: agent, optionsText: 'name'"></select></td>
<td>Remove</td>
</tr>
</tbody>
</table>
Everything binds fine the first time, with the table and select fields appearing properly. However, nothing happens when I change the selected value on any of the select elements. I have bound other elements to them and these don't update, and I've tried using .subscribe() to listen for the update event, but this doesn't fire either.
I expect there's something wrong with the way I'm setting up/binding these relationships, but I can't figure it out to save my life.
Thanks!
I think you need to add
self.agents = ko.observableArray([]);
at the top of ZipcodeUsersViewModel

Categories

Resources