Knockout JS Binding Null Binding - javascript

Here is a fiddle
I have this html:
<div class="margin:0px; padding:0px; outline:0; border:0;" data-bind="with: notesViewModel">
<table class="table table-striped table-hover" data-bind="with: notes">
<thead><tr><th>Date Logged</th><th>Content</th><th>Logged By</th><th></th></tr>
</thead>
<tbody data-bind="foreach: allNotes">
<tr>
<td data-bind="text: date"></td>
<td data-bind="text: compressedContent"></td>
<td data-bind="text: logged"></td>
<td><img src="/images/detail.png" data-bind="click: $root.goToNote.bind($data, $index())" width="20" alt="Details"/></td>
</tr>
</tbody>
</table>
<div class="noteView" data-bind="with: chosenNote">
<div class="info">
<p><label>Date:</label><span data-bind="text: date"></span></p>
<p><label>Logged:</label><span data-bind="text: logged"></span></p>
</div>
<p class="message" data-bind="html: content"></p>
<button class="btn btn-default" data-bind="click: $root.toNotes">Back to Notes</button>
</div>
<div class="editor-label" style="margin-top:10px">
Notes
</div>
<div class="editor-field">
<textarea id="contact_note" rows="5" class="form-control" data-bind="value: $root.noteContent"></textarea>
<p data-bind="text: $root.characterCounter"></p>
<button class="btn btn-info" data-bind="click: $root.saveNotes">Save</button>
<div data-bind="html: $root.status">
</div>
</div>
</div>
And this JavaScript using knockout:
var notesViewModel = function () {
var self = this;
self.notes = ko.observable(null);
self.chosenNote = ko.observable();
self.allNotes = new Array();
self.user = "user1";
// behaviours
self.goToNote = function (noteIndex) {
self.notes(null);
self.chosenNote(new note(self.allNotes[noteIndex]));
};
self.toNotes = function () {
self.chosenNote(null);
self.notes({ allNotes: $.map(self.allNotes, function (item) { return new note(item); }) });
console.log(self.notes());
}
self.noteContent = ko.observable();
self.saveNotes = function () {
var request = $.ajax({
url: "EnquiryManagement/Contact/SaveNotes",
type: "GET",
dataType: "json",
data: { id: "1322dsa142d2131we2", content: self.noteContent() }
});
request.done(function (result, message) {
var mess = "";
var err = false;
var imgSrc = "";
if (message = "success") {
if (result.success) {
mess = "Successfully Updated";
imgSrc = "/images/tick.png";
self.allNotes.push({ date: new Date().toUTCString(), content: self.noteContent(), logged: self.user });
self.toNotes();
} else {
mess = "Server Error";
imgSrc = "/images/redcross.png";
err = true;
}
} else {
mess = "Ajax Client Error";
imgSrc = "/images/redcross.png";
err = true;
}
self.status(CRTBL.CreateMessageOutput(err, mess, imgSrc));
self.noteContent(null);
setTimeout(function () {
self.status(null);
}, 4000);
});
};
self.status = ko.observable();
self.characterCounter = ko.computed(function () {
return self.noteContent() == undefined ? 0 : self.noteContent().length;
});
};
var note = function (data) {
var self = this;
console.log(data.date);
self.date = CRTBL.FormatIsoDate(data.date);
self.content = data.content;
self.compressedContent = data.content == null ? "" : data.content.length < 25 ? data.content : data.content.substring(0, 25) + " ...";
self.logged = data.logged;
console.log(this);
};
ko.applyBindings(new notesViewModel());
When I first load the page it says:
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: notes is not defined;
Bindings value: with: notes
However, I pass it null, so it shouldn't show anything, because when I do the function goToNote then do goToNotes it sets the notes observable to null
So why can't I start off with this null value?

The problem is where you have:
<div data-bind="with: notesViewModel">
That makes it look for a property "notesViewModel" within your notesViewModel, which does not exist.
If you only have one view model you can just remove that data binding and it will work fine.
If, however, you wish to apply your view model to just that div specifically and not the entire page, give it an ID or some other form of accessor, and add it as the second parameter in applyBindings, as follows:
HTML:
<div id="myDiv">
JS:
ko.applyBindings(new notesViewModel(), document.getElementById('myDiv'));
This is generally only necessary where you have multiple view models in the same page.

Like what bcmcfc has put, however, due to my scenario being a multi-viewModel scenario I don't think his solution is quite the right one.
In order to achieve the correct results, first of all I extrapolated out the self.notes = ko.observable(null); into a viewModel which makes doing the table binding far easier.
Then to fix the binding issues instead of setting an element for the bind to take place, I merely did this:
ko.applyBindings({
mainViewModel: new mainViewModel(),
notesViewModel: new notesViewModel()
});
In my original code I have two viewModels which is why I was getting this error. With this method the key is:
I don't create dependancies!
Instead of tieing the viewModel to a certain dom element which can change quite easily and cause having to go and changes things with ko, plus if I add more viewModels then it can get more complicated. I simply do:
data-bind="with: viewModel"
That way I can bind to any DOM object and I can have has many as I like.
This is the solution that solved my post.
Here is the jsfiddle

Related

Hide button everywhere besides specific URL in knockout

I have the following button:
<button class="btn actionButtonIcon" id="DashboardEdit" data-bind="click: changeButtonText">
<figure>
<img src="../../../Images/NotesPink.png" />
<figcaption data-bind="text: $data.ProcurementbuttonText() ? 'Save': 'Edit'"></figcaption>
</figure>
</button>
I want to only show it in this specific url
http://localhost:5595/#scorecard/ec5aa8ed-2798-4e71-b13d-f3e525994538/dashboard/PrefDashBoard
Bearing in mind that ec5aa8ed-2798-4e71-b13d-f3e525994538 is an id, thats always changing but i want it to show with all ids as well for example the button should show here as well
http://localhost:5595/#scorecard/2356789-234-234d-g3g3-reg456452/dashboard/PrefDashBoard
and i want to hide it where this isnt the url.
I tried the following code but it doesnt seem to work:
<script>
$(document).ready(function(){
if(window.location.pathname.match(/\/dashboard/PrefDashBoard))
{
$(".DashboardEdit").show();
}
else
{
$(".DashboardEdit").hide();
}
});
</script>
Here is the JS of that button:
self.ProcurementbuttonText = ko.observable(false);
self.changeButtonText = function(){
self.ProcurementbuttonText(!self.ProcurementbuttonText())
if (!self.ProcurementbuttonText()){
var data = {
'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
};
PreferentialProcurementDashboardApi.Save(data);
}
}
self.DashboardEdit = ko.computed({
read: function () {
var text = 'Customise your dashboard';
if (!self.EnableScorecardFeatures()) {
text = 'This feature is currently unavailable for this scorecard type';
} else {
if (!self.HasDocumentsRole()) {
text = 'You do not have sufficient rights to access the Supporting Documents view';
}
}
return text;
}
});
i think you can take advantage of the visible binding to show/hide the button based on your criteria
function PageViewModel() {
var self = this;
self.buttonVisible = ko.observable(true);
self.changeButtonText = function() {
self.ProcurementbuttonText(!self.ProcurementbuttonText());
}
self.ProcurementbuttonText = ko.observable(false);
self.buttonText = ko.pureComputed(function() {
return self.ProcurementbuttonText() ? "Save" : "Edit";
});
self.isButtonVisible = ko.computed(function() {
//do some your logic here. just need to return a true or false value;
return self.buttonVisible();
});
self.labelText = ko.pureComputed(function() {
var messageStart = "click to ";
var state = self.buttonVisible() ? 'hide' : 'show';
var messageEnd = " button";
return messageStart + state + messageEnd;
});
}
ko.applyBindings(new PageViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button class="btn actionButtonIcon" id="DashboardEdit" data-bind="click: changeButtonText, visible: isButtonVisible, text: buttonText">
Click me.
</button>
<br/>
<br/>
<label><span data-bind="text: labelText " ></span>
<input type="checkbox" data-bind="checked: buttonVisible" />
</label>
If you have Durandal's router plugin installed and configured, you can also use the activeInstruction() observable to get info about the current route. You can then use this in your computed to check if the current fragment matches your page route.
More info here: http://durandaljs.com/documentation/api#class/Router/property/activeInstruction

KnockoutJS : separate model from modelview

I have a model being used by multiple view models, and i need some other javascript components to update the model, observed by my vm's. I have no idea how to do this since in the tutorial, they "mix" the model in the viewmodel.
Here is my code :
var ConversationModel = {
conversations: ko.observableArray(),
open: function(userId){
for(var i = 0; i < this.conversations.length; i++){
if(this.conversations[i].userId == userId){
return;
}
}
var self = this;
var obj = ko.observable({
userId: userId
});
self.conversations.push(obj);
UserManager.getUserData(userId, function(user){
$.getJSON(Routes.messenger.getConversation, "receiver=" + userId, function(data){
obj.receiver = user;
obj.data = data;
});
});
}
};
function ConversationDialogViewModel() {
var self = this;
this.conversations = ko.computed(function(){
return ConversationModel.conversations;
});
console.log(this.conversations());
this.conversations.subscribe(function(context){
console.log(context);
});
}
You can find a (reasonably) good example here how to combine:
Components
Per page ViewModel
Central ServiceProviders (for example, to call APIs or to provide state information between different components)
Please note the code is ES2015 (new Javascript) but you can also write in plain Javascript if you want. The gulp script includes stringifying any html templates in the components, so they get combined and loaded as one file but are edited as separate elements.
An example component:
const ko = require('knockout')
, CentralData = require('../../service-providers/central-data')
, CentralState = require('../../service-providers/central-state')
, template = require('./template.html');
const viewModel = function (data) {
//Make service providers accessible to data-bind and templates
this.CentralData = CentralData;
this.CentralState = CentralState;
this.componentName = 'Component One';
this.foo = ko.observable(`${this.componentName} Foo`);
this.bar = ko.observableArray(this.componentName.split(' '));
this.barValue = ko.observable("");
this.bar.push('bar');
this.addToBar = (stuffForBar) => {
if(this.barValue().length >= 1) {
this.bar.push(this.barValue());
CentralData.pushMoreData({firstName: this.componentName,secondName:this.barValue()});
}
};
this.CentralState.signIn(this.componentName);
if (CentralData.dataWeRetrieved().length < 10) {
var dataToPush = {firstName : this.componentName, secondName : 'Foo-Bar'};
CentralData.pushMoreData(dataToPush);
}
};
console.info('Component One Running');
module.exports = {
name: 'component-one',
viewModel: viewModel,
template: template
};
and component template:
<div>
<h1 data-bind="text: componentName"></h1>
<p>Foo is currently: <span data-bind="text: foo"></span></p>
<p>Bar is an array. It's values currently are:</p>
<ul data-bind="foreach: bar">
<li data-bind="text: $data"></li>
</ul>
<form data-bind="submit: addToBar">
<input type="text"
name="bar"
placeholder="Be witty!"
data-bind="attr: {id : componentName}, value : barValue" />
<button type="submit">Add A Bar</button>
</form>
<h2>Central State</h2>
<p>The following components are currently signed in to Central State Service Provider</p>
<ul data-bind="foreach: CentralState.signedInComponents()">
<li data-bind="text: $data"></li>
</ul>
<h2>Central Data</h2>
<p>The following information is available from Central Data Service Provider</p>
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>Component Name</th><th>Second Value</th>
</tr>
<!-- ko foreach: CentralData.dataWeRetrieved -->
<tr>
<td data-bind="text: firstName"></td><td data-bind="text: secondName"></td>
</tr>
<!-- /ko -->
</table>
<h3>End of Component One!</h3>
</div>
For your purposes, you can ignore the Central state provider and psuedo APIs, but you might find the model useful as your app gets more complicated.

Bindings doesn't work on nested template loaded by JSON in KnockoutJS

Yesterday I make this question:
How can I refresh or load JSON to my viewModel on Knockout JS with complex models
Everything works OK with the fixes but when I try to use a complex json to load in the viewModel some of the buttons (specifically on Groups) doesn't work.
To resume the problem. I have a json with the previous serialized data. I use that json to fill the viewModel, this works, load correctly the data but the problem are in the "group" template, because the data is loaded but the buttons doesn't work, the only button which is working is the "remove group".
(Please refer to the image)
Any idea to fix this? Thanks.
Jsfiddle example with the problem
http://jsfiddle.net/y98dvy56/26/
!Check this picture.
The red circles indicates the buttons with problems.
The green circles indicates the buttons without problems.
Here is the body html
<div class="container">
<h1>Knockout.js Query Builder</h1>
<div class="alert alert-info">
<strong>Example Output</strong><br/>
</div>
<div data-bind="with: group">
<div data-bind="template: templateName"></div>
</div>
<input type="submit" value="Save" data-bind="click: Save"/>
</div>
<!-- HTML Template For Conditions -->
<script id="condition-template" type="text/html">
<div class="condition">
<select data-bind="options: fields, value: selectedField"></select>
<select data-bind="options: comparisons, value: selectedComparison"></select>
<input type="text" data-bind="value: value"></input>
<button class="btn btn-danger btn-xs" data-bind="click: $parent.removeChild"><span class="glyphicon glyphicon-minus-sign"></span></button>
</div>
</script>
<!-- HTML Template For Groups -->
<script id="group-template" type="text/html">
<div class="alert alert-warning alert-group">
<select data-bind="options: logicalOperators, value: selectedLogicalOperator"></select>
<button class="btn btn-xs btn-success" data-bind="click: addCondition"><span class="glyphicon glyphicon-plus-sign"></span> Add Condition</button>
<button class="btn btn-xs btn-success" data-bind="click: .addGroup"><span class="glyphicon glyphicon-plus-sign"></span> Add Group</button>
<button class="btn btn-xs btn-danger" data-bind="click: $parent.removeChild"><span class="glyphicon glyphicon-minus-sign"></span> Remove Group</button>
<div class="group-conditions">
<div data-bind="foreach: children">
<div data-bind="template: templateName"></div>
</div>
</div>
</div>
</script>
<!-- js -->
<script src="js/vendor/knockout-2.2.1.js"></script>
<script src="js/vendor/knockout-mapping.js"></script>
<script src="js/condition.js"></script>
<script src="js/group.js"></script>
<script src="js/viewModel.js"></script>
<script>
window.addEventListener('load', function(){
var json =
{"group":{"templateName":"group-template","children":[{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"group-template","children":[{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"}],"logicalOperators":["AND","OR"],"selectedLogicalOperator":"AND","text":"(Points = 0 AND Points = 0 AND Points = 0)"}],"logicalOperators":["AND","OR"],"selectedLogicalOperator":"AND","text":"(Points = 0 AND Points = 0 AND Points = 0 AND (Points = 0 AND Points = 0 AND Points = 0))"},"text":"(Points = 0 AND Points = 0 AND Points = 0 AND (Points = 0 AND Points = 0 AND Points = 0))"};
var vm = new QueryBuilder.ViewModel();
ko.mapping.fromJS(json.group, {}, vm.group);
ko.applyBindings(vm);
}, true);
</script>
Condition.js:
window.QueryBuilder = (function(exports, ko){
function Condition(){
var self = this;
self.templateName = 'condition-template';
self.fields = ko.observableArray(['Points', 'Goals', 'Assists', 'Shots', 'Shot%', 'PPG', 'SHG', 'Penalty Mins']);
self.selectedField = ko.observable('Points');
self.comparisons = ko.observableArray(['=', '<>', '<', '<=', '>', '>=']);
self.selectedComparison = ko.observable('=');
self.value = ko.observable(0);
}
exports.Condition = Condition;
return exports;
})(window.QueryBuilder || {}, window.ko);
Group.js
window.QueryBuilder = (function(exports, ko){
var Condition = exports.Condition;
function Group(){
var self = this;
self.templateName = 'group-template';
self.children = ko.observableArray();
self.logicalOperators = ko.observableArray(['AND', 'OR']);
self.selectedLogicalOperator = ko.observable('AND');
// give the group a single default condition
self.children.push(new Condition());
self.addCondition = function(){
self.children.push(new Condition());
};
self.addGroup = function(){
self.children.push(new Group());
};
self.removeChild = function(child){
self.children.remove(child);
};
}
exports.Group = Group;
return exports;
})(window.QueryBuilder || {}, window.ko);
ViewModel.js
window.QueryBuilder = (function(exports, ko){
var Group = exports.Group;
function ViewModel() {
var self = this;
self.group = ko.observable(new Group());
self.load = function (data) {
ko.mapping.fromJS(data, self);
}
self.Save = function () {
console.log(ko.toJSON(self));
}
}
exports.ViewModel = ViewModel;
return exports;
})(window.QueryBuilder || {}, window.ko);
Your issue is caused by the fact that the mapping plugin makes your data observable, but doesn't augment your data with the functions in your model such as the add, remove, etc... functions. If you do a console log for the json data when it's inserted into the view model you will notice that the data is observable but the functions are missing. You need to provide a mapping to customize your Group, Condition, etc.. constructors. Because the children array in your case is of mixed types (condition or group) Here is a custom mapping to take care of that:
var childrenMapping = {
'children': {
create: function(options) {
var data = options.data;
console.log(data);
var object;
switch(data.templateName) {
case 'condition-template':
object = new QueryBuilder.Condition(data);
break;
case 'group-template':
object = new QueryBuilder.Group(data);
break;
}
return object;
}
}
};
Then you simply need to provide this mapping in your initial mapping
ko.mapping.fromJS(json.group, childrenMapping, vm.group);
Then inside the constructor of the Group object:
function Group(data){
var self = this;
self.templateName = 'group-template';
...
ko.mapping.fromJS(data, childrenMapping, this);
}
You also need to update the Condition constructor to accept the data provided by the mapping, but since conditions don't have children you do not need to provide the childrenMapping here:
function Condition(data){
var self = this;
self.templateName = 'condition-template';
...
ko.mapping.fromJS(data, {}, this);
}
I've the mapping at the end of both function so that the mapped values override you initial value.
The updated jsfiddle here:
http://jsfiddle.net/omerio/y98dvy56/32/
This answer is related:
knockout recursive mapping issue

KnockoutJS with PagerJS stop working after data bound

I'm working on KnockoutJS with PagerJS plugin and found this problem. I don't know if it is related to PagerJS or not but here's the problem.
I use page binding of pager.js with sourceOnShow property and there are child page inside the source contents bound with an observable property of its parent's ViewModel.
When the observable property changes, the child tried to update new data. But after the first value is bound, it seems it was stopped working. I put some logs in between each steps and the result comes as follows:
The result of my sample code displays only the job_id, the rest displays blocks with empty bindings and the console logged only log1 and log2. No other errors logged. As if it stopped working after the first binding.
my code is, for example
the main page
<script src="/js/jobspage.js"></script>
<!-- some elements -->
<div data-bind="page: {
id: 'somepage',
title: 'Some Page',
sourceOnShow: 'template/somepage',
role: 'start'
}"></div>
<div data-bind="page: {
id: 'jobs',
title: 'Jobs',
sourceOnShow: 'template/jobs',
with: JobsPageVM
}"></div>
<div data-bind="page: {
id: 'other',
title: 'Other Page',
sourceOnShow: 'template/otherpage'
}"></div>
the /template/jobs
<div class="jobs" id="main" role="main">
<div class="job-list" data-bind="page: {role: 'start'}">
<!-- ko foreach: jobitems -->
<div data-bind="event: {click: item_clicked}">
<!-- item description -->
<!-- item_clicked will set the selectedItem (observable) property of JobsPageVM -->
</div>
<!-- /ko -->
</div>
<div class="job-info" data-bind="page: {id: 'jobinfo', with: selectedItem}">
<!--ko text: console.log('log1')--><!--/ko-->
<!-- some elements -->
<!--ko text: console.log('log2')--><!--/ko-->
Job ID : <span class="job-value" data-bind="text: job_id"></span>
<!--ko text: console.log('log3')--><!--/ko-->
Job Title : <span class="job-value" data-bind="text: job_title"></span>
<!--ko text: console.log('log4')--><!--/ko-->
</div>
</div>
the jobspage.js
var JobsPageVM = function () {
var self = this;
var dataitems = ko.observableArray();
self.isLoading = ko.observable(true);
self.searchTerm = ko.observable("");
self.jobitems = ko.computed(function () {
var search_input = self.searchTerm().toLowerCase();
if (search_input === "") {
return dataitems();
} else {
return ko.utils.arrayFilter(dataitems(), function (item) {
var data = item.cust_first_name + item.cust_last_name;
return data.search(new RegExp(search_input, "i")) >= 0;
});
}
}, this);
self.selectedItem = ko.observable();
self.branchID = ko.observable(sample_branch_id);
self.getJobList = function (status) {
self.isLoading(true);
if (typeof (status) === "undefined") {
status = "all";
}
$.ajax({
url: "/api/job/branch/" + self.branchID(),
data: {
jobstatus: status
},
success: function (data) {
dataitems(data); // data is an array of object items contains `job_id`, `job_title`, and more
self.isLoading(false);
},
error: function (x, s, e) {
console.log(x, s, e);
self.isLoading(false);
}
});
};
self.item_clicked = function (vm, e) {
self.selectedItem(vm);
pager.navigate('jobs/jobinfo');
};
self.getJobList();
};
*I don't know whether it against the rule or not. This question was asked before but didn't answered, so I deleted and re-asking here. Thanks to #Stijn and #KristianNissen for help refine my question.
I found a kind of workaround, or maybe the solution. But I didn't quite sure the cause of the problem.
Originally, I tried to bind the selectedItem to the page: {with: ...} binding which resulted the problem above. Now I changed the binding of selectedItem with the element itself instead of inside page: binding.
I changed from this :
<div class="job-info" data-bind="page: {id: 'jobinfo', with: selectedItem}">
To this :
<div class="job-info" data-bind="page: {id: 'jobinfo'}, with: selectedItem">
And it seems to work fine now.

Find <span> value after ko.applyBindings

I'm getting some values from webapi using knockout.js and then result of that (holded in span) I'm trying to use in the other place (input in table row). Result I'm showing this way:
<h3 data-bind="foreach: book">
<span data-bind="text: Hotel" class="label label-info"/>
<span data-bind="text: Номер" class="label label-info"/>
<span class="label label-info" data-bind=" text: Фамилия"/>
<span class="label label-info ad" data-bind=" text: Колчел"/>
<span class="label label-info ch" data-bind=" text: Дети"/>
</h3>
and this is knockout code:
<script>
function BookViewModel(baseUri) {
var self = this;
self.Номер = ko.observable("");
self.Колчел = ko.observable("");
self.Дети = ko.observable("");
self.Фамилия = ko.observable("");
self.Hotel = ko.observable("");
var book = {
Номер: self.Номер,
Колчел: self.Колчел,
Дети: self.Дети,
Фамилия: self.Фамилия,
Hotel: self.Hotel
};
self.book = ko.observable();
self.books = ko.observableArray();
$.getJSON(baseUri, self.book);
}
$(document).ready(function () {
var url = location.href.split("/")
var baseUri;
if (url[4].toString = 'x') {
baseUri = '/api/xTourist/' + url[5];
}
else if (url[4].toString = 'y') {
baseUri = '/api/yTourist/' + url[5];
}
ko.applyBindings(new BookViewModel(baseUri));
//This is how I'm trying to read result and use this result in input field in the other table.
var ad = $("span.ad").val();
var ch = $("span.ch").val();
$("#gvOrders tr input.pax_ad").each(function () {
$(this).val(ad);
});
$("#gvOrders tr input.pax_ch").each(function () {
$(this).val();
});
});
</script>
Unfortunately this var is undefrined. I'm really don't understand why values cannot be readed after ko already apply binding.
The knockout documentation is really good. I suggest you start there to help get a better understanding of how knockout works. It'll really save you some time and frustration.
As for the $.getJSON call, the documentation has lots of information and examples.

Categories