Foreach not updating HTML list elements - asp.net-mvc

Using knockout 2.2.0
I'm trying to use the same dialog for add and edit. I have the code mostly working, but when I replace the observable with the new edited one, it doesn't cause an update in the foreach (or at least it continues to display the old values) It does update the actual model, as I can see in dev tools. I even tried to force an update with .valueHasMutated(), but with no luck.
self.editReference = function () {
self.isEdit(true);
self.open();
self.dialogReferences(this);
};
self.saveEditReference = function () {
self.references.replace(this, self.dialogReferences);
self.references.valueHasMutated();
self.dialogReferences(newReferences());
self.close();
};
And here is the some of the partial view with the references section of HTML code:
<ul class="sortable references-summary" data-bind="foreach: references">
<li class="ui-state-default"><b>Name: </b><!-- ko text:name --><!-- /ko--><br /><b>Company: </b><!-- ko text:company --><!-- /ko--><span class="ui-icon ui-icon-closethick"></span><span class="ui-icon ui-icon-wrench"></span></li>
</ul>

Thanks to CrimsonChris for pointing out my bug. The updated code below works as expected.
The approach is to have a reference you are editing, in addition to the references in your array. When you start to edit, you copy the values from the array to your edit reference. When you save the edit, you copy them back. There is no need for valueHasMutated for this to work.
function reference(name, company) {
return {
name: ko.observable(name),
company: ko.observable(company)
};
}
// Copy r1 into r2
reference.copy = function(r1, r2) {
r2.name(r1.name());
r2.company(r1.company());
}
var self = {
editingReference: undefined,
dialogReferences: reference('', ''),
references: ko.observableArray([
reference('One', 'First Company'),
reference('Two', '2nd Company')
]),
dialogIsOpen: ko.observable(false),
open: function() {
self.dialogIsOpen(true);
},
close: function() {
self.dialogIsOpen(false);
}
};
self.editReference = function(item) {
self.editingReference = item;
self.open();
reference.copy(item, self.dialogReferences);
};
self.removeReference = function(item) {
self.references.remove(item);
self.close();
};
self.saveEditReference = function(item) {
reference.copy(item, self.editingReference);
self.close();
};
ko.applyBindings(self);
<link href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<ul class="sortable references-summary" data-bind="foreach: references">
<li class="ui-state-default"> <b>Name: </b>
<!-- ko text:name() -->
<!-- /ko-->
<br /> <b>Company: </b>
<!-- ko text:company() -->
<!-- /ko--> <span class="ui-icon ui-icon-closethick"></span>
<span class="ui-icon ui-icon-wrench"></span>
</li>
</ul>
<div data-bind="if: dialogIsOpen">
<div data-bind="with:dialogReferences">
<label>Name</label>
<input data-bind="value:name" />
<br/>
<label>Company</label>
<input data-bind="value:company" />
<input type="button" value="Save" data-bind="click: $parent.saveEditReference" />
</div>
</div>

Related

knockout.js ul li databinding not proper

HTML
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />
JS
function AppViewModel() {
var self = this;
self.cardtext=ko.observable();
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function() {
self.people.push({ name: self.cardtext });
};
self.removePerson = function() {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
This is the result
The problem is that the textbox keep adding new elements but the previous newly added elements keep getting updated by the new elements.
3rd element was 3rd element
4th element was 4th element
when I added 5th element the 3rd and the 4th element get updated by 5th element. why it is that? what I am doing wrong?. I have no idea.
You just need to add () at the end of self.cardtext(). If you don't put the parenthesis, what it will do is it will push the observable object of cardtext to the array instead of its value. So when you modify cardtext from the textbox, it will also modify the previous object that was pushed.
function AppViewModel() {
var self = this;
self.cardtext=ko.observable();
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function() {
self.people.push({ name: self.cardtext() });
};
self.removePerson = function() {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
<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>
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />

AngularJS doesn't work in MVC Partial Views

I'm currently working on a ASP.NET MVC project. The sites of the web application are created with Bootstrap. Later I added some AngularJS script to be able to translate the page into different languages. This works fine for all the pages, but not so if a partial view is loaded from a page.
So, for example I have a page to search for rollout objects by name or host name. On the page all the angular expressions in curly braces are evaluated properly and are replaced with strings in several languages by using a translate script. Now if I filter the objects by one of the three attributes the partial view for that page is loaded showing the results of the search, but here are the angular expressions not evaluated and it just shows the expressions themselves.
Here is the page where it works properly:
#{
ViewBag.Title = "{{ 'ROLLOUT-OBJECT_MANAGEMENT.TITLE' | translate }}";
}
<!-- html -->
<div style="font-size: 20px; margin-top: 20px; margin-bottom: 20px;">
<div class="gray-background list-group-item" translate="{{'ROLLOUT-OBJECT_MANAGEMENT.TITLE'}}"></div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<div class="row margin-bottom">
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.FIRST_NAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.SURNAME'}}"></h6>
</div>
<div class="col-md-3">
<h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.HOST_NAME'}}"></h6>
</div>
</div>
<div class="row margin-bottom">
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iFirstName" name="iFirstName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iSurName" name="iSurName" placeholder="">
</div>
<div class="col-md-3">
<!-- referenced in getPartial() -->
<input type="text" class="form-control" id="iHostName" name="iHostName" placeholder="">
</div>
<div class="col-md-3">
<!-- getPartial() added to click through javascript-->
<button type="submit" class="btn btn-primary btn-block" id="iButton"><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.BUTTON_SEARCH'}}"></span><span class="white-color glyphicon glyphicon-search"></span></button>
</div>
</div>
</div>
</div>
<div class="list-group">
<div class="gray-background list-group-item">
<h5><span translate="{{'ROLLOUT-OBJECT_MANAGEMENT.RESULTS'}}"></span><span class="purple-color glyphicon glyphicon-globe"></span></h5>
</div>
<!-- referenced in getPartial() -->
<div class="gray-background list-group-item">
<div class="row">
<div class="col-md-12" id="partialViewContainer">
#{Html.RenderPartial("_RolloutObjectManagementResultsPartial");}
</div>
</div>
</div>
</div>
<!-- layout -->
#Styles.Render(
"~/content/chosen/chosen.css",
"~/content/chosen/prism.css",
"~/content/chosen/style.css",
"~/content/bootstrap.css",
"~/content/Site.css")
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script>
//add functionality to button
$('#iButton').click(function () {
getPartial('0');
});
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
//alert(xhr.responseText);//debug
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
And here is the partial view where it doesn't work (important are the expressions in {{...}}:
<!-- Import needed namespaces -->
#using RolloutTool.BusinessLayer.Foundation
#using RolloutTool.Utility
<!-- Initializing needed variables -->
#{
List<RolloutObject> RolloutObjects = ViewContext.Controller.ViewBag.RolloutObjects;
List<Cluster> Clusters = ViewContext.Controller.ViewBag.Clusters;
string name = "";
int count = 0;
string rowID = "";
int page = 0;
if (ViewContext.Controller.ViewBag.Page != null)
{
page = ViewContext.Controller.ViewBag.Page;
}
}
<!-- html elements -->
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EMPLOYEE'}}"></h6></th>
<th style="width:20%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.WORK_STATION'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.EDIT'}}"></h6></th>
<th class="text-center" style="width:25%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.CLUSTER'}}"></h6></th>
<th class="text-center" style="width:15%"><h6 translate="{{'ROLLOUT-OBJECT_MANAGEMENT.ASSIGN'}}"></h6></th>
</tr>
</thead>
<tbody>
<!-- creating all RolloutObject Table rows -->
#foreach (RolloutObject ro in RolloutObjects)
{
<!-- generating rowID -->
rowID = "row" + Convert.ToString(count);
count++;
<!-- generating the full employee name -->
name = Functions.TryGetValue(ro.Employee.FirstName) + " " + Functions.TryGetValue(ro.Employee.SecondName) + " " + Functions.TryGetValue(ro.Employee.Name);
<tr id="#rowID">
<td>#name</td>
<td id="#Convert.ToString(rowID + "_hn")">#Convert.ToString(Functions.TryGetValue(ro.Hostname))</td>
<!-- generate link to right rolloutobjectedit -->
<td class="text-center"><span class="btn-pencil glyphicon glyphicon-pencil blue-color glyph-hov" onclick="location.href='#Url.Action("RolloutObjectEdit", "RolloutObject", new {hostName = ro.Hostname })'"></span></td>
<!-- generating the link for cluster addition and populating cluster dropdown -->
<td class="text-center">
<div class="row">
<div class="col-sm-12">
<select class="chosen-select no-margin" style="width:100%" id="#Convert.ToString(rowID + "_cl")" name="iCluster" data-placeholder="Cluster">
#if (ro.Cluster != null)
{
<option selected>#Convert.ToString(Functions.TryGetValue(ro.Cluster.Name))</option>
}
else
{
<option></option>
}
#foreach (Cluster cluster in Clusters)
{
<option>#Convert.ToString(Functions.TryGetValue(cluster.Name))</option>
}
</select>
</div>
</div>
</td>
<td class="text-center"><span class="btn-ok glyphicon glyphicon-ok green-color glyph-hov" onclick="callAjax('#rowID')" /></td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input class="hidden" id="hPage" value="#Convert.ToString(page)" />
<nav>
<ul class="pager">
<li class="pull-left"><a class="btn-paging glyphicon glyphicon-arrow-left" onclick="previous()"></a></li>
<li class="pull-right"><a class="btn-paging glyphicon glyphicon-arrow-right" onclick="next()"></a></li>
</ul>
</nav>
</div>
</div>
<!-- javascript -->
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script>
function callAjax(idRow) {
//get row values
var tempTD = document.getElementById(idRow + "_hn");
var tempSelect = document.getElementById(idRow + "_cl");
var tempHostName = tempTD.textContent;
var tempCluster = tempSelect.options[tempSelect.selectedIndex].text;
//ajax call
$.ajax({
url: "AddToCluster",
type: "POST",
data: { clusterName: tempCluster, hostName: tempHostName },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
<script>
function previous() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
if (temp > 0) {
temp = --temp;
}
getPartial(temp);
}
function next() {
var temp = document.getElementById("hPage").value;
//alert(temp);//debug
temp = ++temp;
getPartial(temp);
}
</script>
<script>
function getPartial(newPage) {
//get search values
var tempFirst = document.getElementById("iFirstName");
var tempSur = document.getElementById("iSurName");
var tempHost = document.getElementById("iHostName");
var firstResult = tempFirst.value;
var surResult = tempSur.value;
var hostResult = tempHost.value;
//ajax call
$.ajax({
url: "_RolloutObjectManagementResultsPartial",
type: "POST",
data: { firstName: firstResult, surName: surResult, hostName: hostResult, page: newPage, count: 10 },
dataType: "html",
error: function (xhr) {
alert(xhr.responseText);
},
success: function (result) {
$("#partialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
})
},
complete: function () {
//alert("everything worked");//debug
}
});
}
</script>
This is the _Layout.cshtml where the scripts are contained and loaded:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - {{ 'TITLE.PROGRAM' | translate }}</title>
#Styles.Render(
"~/Content/css",
"~/Content/flag-icon-css-master/assets/docs.css",
"~/Content/flag-icon-css-master/css/flag-icon.min.css",
"~/Content/Site.css")
<script src="~/Scripts/angular/angular.js"></script>
<script src="~/Scripts/angular/angular-translate.js"></script>
<script src="~/Scripts/angular/angular-cookies.min.js"></script>
<script src="~/Scripts/angular/translate.js"></script>
<script src="~/Scripts/angular/angular-route.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-cookie.min.js"></script>
<script src="~/Scripts/angular/angular-translate-storage-local.min.js"></script>
</head>
<body ng-controller="Ctrl">
<!-- Here is the html for the navigation bar etc. -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
I am really not an expert on AngularJS as I only wanted to provide some cool translation feature, but I hope you guys have an idea why it doesn't work in the partial views.
Its just that you need to call the partial view using ng-include("'controller/action'"). Apostrophe(') is important while writing url.
Example
<div id="TestDiv" ng-include="templateUrl"></div>
and inside the angular controller
var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope, $http, $sce) {
//Initially
$scope.templateUrl = '/Home/DefaultPage';
// To dynamically change the URL.
$scope.NewProjFn = function () {
$scope.templateUrl = '/Home/ProjectPage';
};
});
It might well not at all be difficult for you to re-implement it but by using ng-include you also need not to make an ajax call. It do it all by itself which includes ajax call, compilation and display. But the functions like ng-click and other events will not work as its a one time compilation process.

dynamic jQuery Mobile SelectMenu is prematurely styling

Knockout is dynamically adding a select menu to a jQuery Mobile page. When it appears it has some select menu styling even though it hasn't been initialized as one. This causes a problem when I do initialize it because then it is wrapped in an extra ui-select. What is causing this and how can I fix it?
Here is an example. Check 'show options' to display the select. Then click one of the buttons to see the problem.
http://jsfiddle.net/5udqV/1/
Looking at your fiddle, the select is not dynamic, only the options within the select are. So one thing you could do is in the markup add data-role="none" to the select so that jQM does not touch it during page initialization. Then when you call .selectmenu() it will look right.
Your updated FIDDLE
UPDATE:
Use proper jQM structure and events:
DEMO
<div data-role="page" id="page1">
<div data-role="header">
<h1>My page</h1>
</div>
<div role="main" class="ui-content">show options
<input type="checkbox" data-bind="checked: showOptions" />
<br />
<div data-bind="if: showOptions">
<select data-bind="options: options, value: selectedOption"></select>
</div>
<button id="a">create select</button>
<button id="b">refresh select</button>
<button id="c">create page</button>
<div data-bind="text: ko.toJSON($root)"></div>
</div>
</div>
var vm = {
options: ["A", "B", "C"],
showOptions: ko.observable(),
selectedOption: ko.observable("B")
};
ko.applyBindings(vm);
$(document).on("pagecreate", "#page1", function () {
$('button').on("click", function () {
var id = $(this).prop("id");
if (id == "a") {
$("select").selectmenu();
} else if (id == "b") {
$("select").selectmenu("referesh");
} else if (id == "c") {
$(".ui-page").trigger("create");
}
});
});

jQuery Mobile and Knockout.js templating, styling isnt applied

Ok so this is beginning to drive me insane. I have for several hours now searched and searched, and every single solution doesnt work for me. So yes, this question might be redundant, but i cant for the life of me get solutions to work.
I have a bunch of checkboxes being generated by a jquery template that is databound via knockout.js. However, it turns up unstyled. Afaik, it is something about jquery mobile does the styling before knockout renderes the template, so it ends up unstyled.
I have tried numerous methods to no avail, so i hope someone here can see what i am doing wrong.
(i am using jquery mobile 1.2.0 , jquery 1.8.2 and knockout 2.2.1)
This is the scripts:
<script type="text/javascript">
jQuery.support.cors = true;
var dataFromServer = "";
// create ViewModel with Geography, name, email, frequency and jobtype
var ViewModel = {
email: ko.observable(""),
geographyList: ["Hovedstaden","Sjælland","Fyn + øer","Nordjylland","Midtjylland","Sønderjylland" ],
selectedGeographies: ko.observableArray(dataFromServer.split(",")),
frequencySelection: ko.observable("frequency"),
jobTypes: ["Kontor (administration, sekretær og reception)","Jura","HR, Ledelse, strategi og udvikling","Marketing, kommunikation og PR","Handel og service (butik, service, værtinde og piccoline)","IT","Grafik og design","Lager, chauffør, bud mv.","Økonomi, regnskab og finans","Kundeservice, telefoninterview, salg og telemarketing","Sprog","Øvrige jobtyper"],
selectedJobTypes: ko.observableArray(dataFromServer.split(",")),
workTimes: ["Fulltid","Deltid"],
selectedWorkTimes: ko.observableArray(dataFromServer.split(","))
};
// function for returning checkbox selection as comma separated list
ViewModel.selectedJobTypesDelimited = ko.dependentObservable(function () {
return this.selectedJobTypes().join(",");
}, ViewModel);
var API_URL = "/webapi/api/Subscriptions/";
// function used for parsing json message before sent
function omitKeys(obj, keys) {
var dup = {};
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.indexOf(key) === -1) {
dup[key] = obj[key];
}
}
}
return dup;
}
//Function called for inserting new subscription record
function subscribe() {
if($("#jobmailForm").valid()=== true){
//window.alert("add subscriptiooncalled");
var mySubscription = ko.toJS(ViewModel);
//var json = JSON.stringify(mySubscription);
var jsonSmall = JSON.stringify(omitKeys(mySubscription, ['geographyList','jobTypes','selectedJobTypesDelimited','workTimes']));
//window.alert(jsonSmall);
$.ajax({
url: API_URL,
cache: false,
type: 'POST',
contentType: 'application/json',
data: jsonSmall,
success: function (data) {
window.alert("success");
},
error: function (error) {
window.alert("ERROR STATUS: " + error.status + " STATUS TEXT: " + error.statusText);
}
});
}
}
function initializeViewModel() {
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
}
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
initializeViewModel();
$('#jobmailDiv').trigger('updatelayout');
});
</script>
<script id="geographyTmpl" type="text/html">
<input type="checkbox" data-role="none" data-bind="attr: { value: $data }, attr: { id: $data }, checked: $root.selectedGeographies" />
<label data-bind="attr: { for: $data }"><span data-bind="text: $data"></span></label>
</script>
<script id="jobTypeTmpl" type="text/html">
<label><input type="checkbox" data-role="none" data-bind="attr: { value: $data }, checked: $root.selectedJobTypes" /><span data-bind="text: $data"></span></label>
</script>
Note, "jobmail" is the surrounding "page" div element, not shown here. And this is the markup:
<div data-role="content">
<umbraco:Item field="bodyText" runat="server"></umbraco:Item>
<form id="jobmailForm" runat="server" data-ajax="false">
<div id="jobmailDiv">
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" class="required email" data-bind="'value': email" />
</p>
<fieldset data-role="controlgroup" data-mini="true" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }">
<input type="checkbox" id="lol" />
<label for="lol">fkfkufk</label>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<p data-bind="template: { name: 'jobTypeTmpl', foreach: jobTypes, templateOptions: { selections: selectedJobTypes } }"></p>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<input type="radio" id="frequency5" name="frequency" value="5" data-bind="checked: frequencySelection" /><label for="frequency5">Højst 5 gange om ugen</label>
<input type="radio" id="frequency3" name="frequency" value="3" data-bind="checked: frequencySelection" /><label for="frequency3">Højst 3 gange om ugen</label>
<input type="radio" id="frequency1" name="frequency" value="1" data-bind="checked: frequencySelection" /><label for="frequency1">Højst 1 gang om ugen</label>
</fieldset>
<p>
<input type="button" value="Tilmeld" class="nice small radius action button" onClick="subscribe();">
</p>
Tilbage
</div>
</form>
Alternate method of invoking the restyling (doesnt work either):
$(document).on('pagebeforeshow', '#jobmail', function(){
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
});
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
$('#jobmail').trigger('pagecreate');
});
Use a custom binding (Knockout) to trigger jQuery Mobile to enhance the dynamically created content produced by Knockout.
Here is a simple custom binding:
ko.bindingHandlers.jqmEnhance = {
update: function (element, valueAccessor) {
// Get jQuery Mobile to enhance elements within this element
$(element).trigger("create");
}
};
Use the custom binding in your HTML like this, where myValue is the part of your view model that changes, triggering the dynamic content to be inserted into the DOM:
<div data-bind="jqmEnhance: myValue">
<span data-bind="text: someProperty"></span>
My Button
<input type="radio" id="my-id" name="my-name" value="1" data-bind="checked: someOtherProperty" /><label for="my-id">My Label</label>
</div>
In my own case, myValue was part of an expression in an if binding, which would trigger content to be added to the DOM.
<!-- ko if: myValue -->
<span data-bind="jqmEnhance: myValue">
<!-- My content with data-bind attributes -->
</span>
<!-- /ko -->
Every dynamically generated jQuery Mobile content must be manually enhanced.
It can be done in few ways, but most common one can be done through the jQuery Mobile function .trigger( .
Example:
Enhance only page content
$('#page-id').trigger('create');
Enhance full page (header + content + footer):
$('#page-id').trigger('pagecreate');
If you want to find more about this topic take a look my other ARTICLE, to be more transparent it is my personal blog. Or find it HERE.

Knockout refresh observableArray in the html

I'm working on Android with Jquery Mobile with PhoneGap using Knockout for loading data.
I'm getting the data all right and loading it on the HTML page accordingly to the for each data-bind I have on the tags.
When I want to refresh the data, it just doesn't do it. It returns just an HTML without bound data or throwing dom exception not found.
My applyBinding happens inside pagecreate event of the page.
I've posted a simple example describing the problem on my SkyDrive - http://sdrv.ms/LpUdLt
It's a public example reproducing the problem.
the viewmodel holds an array that holds array.
refreshed with randomal values.
trying to reload the page in jquery mobile with changepage reload with new data by pressing the navbar button fails with the dom object mistake.
I do agree not to that I shouldn't create an instance of VM every page create, just can't find a way to implement it, so that the data will be rerendered on HTML.
//indexPage.js
var wAViewModelInst ;
var viewPageIndexContent;
$('#pageIndex').live('pagecreate', function (event) {
viewPageIndexContent = document.getElementById("pageIndexContent");
wAViewModelInst = new WAViewModel(true);
ko.applyBindings(wAViewModelInst, viewPageIndexContent);
waHeaderVM.refreshContentData = function () {
// wAViewModelInst.updateRowList();
// ko.cleanNode(viewPageIndexContent);
// viewPageIndexContent = document.getElementById("pageIndexContent");
//wAViewModelInst = new WAViewModel(true);
//ko.applyBindings(wAViewModelInst, viewPageIndexContent);
$.mobile.changePage("index.html", { allowSamePageTransition: true, reloadPage: true });
$.mobile.hidePageLoadingMsg();
}
}
//WAViewModel
self.WARowList = ko.observableArray();
self.updateRowList = function () {
self.WARowList(self.GetWA());
}
//tried the exteding
//ko.observableArray.fn.WARowListUpdate = function () {
// //create a sub-observable
// this.hasItems = ko.observable();
// //update it when the observableArray is updated
// this.subscribe(function (newValue) {
// this.hasItems(newValue && newValue.length ? true : false);
// }, this);
// //trigger change to initialize the value
// this.valueHasMutated();
// //support chaining by returning the array
// return this;
//};
is there any way to update the html after the first rendering ?
adding the html code:
<div id="pageIndex" data-role="page" data-transition="flip" data-theme="e" data-dom-cache="true">
<div id="indexHeader" data-role="header" data-theme="e">
<div data-role="navbar" data-iconpos="right">
<ul>
<li><a href="login.html" data-role="tab" data-icon="back" data-bind="click: loadingHandler"
class="brighter-text">חזרה</a></li>
<li><a href="#" data-role="tab" data-icon="refresh" data-bind ="click: refreshContentData" >רענן</a></li>
<li>ביצוע חקר</li>
<li><a href="#" data-role="tab" data-icon="grid" class="ui-btn-active brighter-text">
סידור עבודה</a></li>
</ul>
</div>
</div>
<div id="pageIndexContent" data-role="content" data-theme="e" style="padding-bottom: 52px;
height: 570px;">
<h2 data-bind="text:Title" class="brighter-text" style="font-size:22pt;">
</h2>
<div data-bind="foreach: WARowList" style="width: 99%; text-align: center">
<div>
<table style="float: right; width: 20%; height: 60px;" cellpadding="0" cellspacing="0">
<tr data-bind="visible : FirstRow " style="height: 31px;">
<th class="AlignedHeader">
<label>
שעה / שילוט</label>
</th>
</tr>
<tr data-bind="style: { backgroundColor: Odd() ? '#8CC63F' : '#AFC493' }">
<td style="width: 20%;" data-bind="style: { backgroundColor: IsNew() ? 'yellow' : 'transparent' }">
<input type="button" data-bind="click: ShowSampleDetails, value: ShilutTime , jQueryButtonUIEnableDisable:$data"
data-icon="plus" data-iconpos="right"/>
</td>
</tr>
</table>
<table style="height: 60px; width: 80%; background-color: #8CC63F;" data-bind="style: { backgroundColor: Odd() ? '#8CC63F' : '#AFC493' }"
cellpadding="0" cellspacing="0">
<thead data-bind="if : FirstRow">
<tr data-bind="foreach: CellList">
<th class="AlignedHeader">
<label data-bind="text: Date">
</label>
</th>
</tr>
</thead>
<tbody>
<tr data-bind="foreach: CellList">
<td style="width: 11.5%;">
<div data-bind="visible:IsPopulated ">
<div data-bind="visible: HasDrivers">
<input type="button" data-role="button" data-bind="click: ShowBusDriverList.bind($data , $root) , jQueryButtonUIEnableDisable: $data "
data-icon="search" data-iconpos="right" value="נהגים" class="brighter-text" />
</div>
<div data-bind="visible: !HasDrivers()">
<input type="button" data-role="button" id="btnNoDriver" disabled="disabled" data-icon="info"
data-iconpos="right" value="אין נהג" class="brighter-text" />
</div>
</div>
<div data-bind="visible: !IsPopulated">
</div>
</td>
</tr>
</tbody>
</table>
</div>
and so on ..
the GetWA function returns an observableArray of warow list .
it works the first time the trouble is rerendering the dom object.
the dom element is contaminated with ko and fails ..
I tried the answer of Luffy :
var lVM = new loginViewModel();
var footerViewModelLogin = {
IsOnline: ko.observable(globalContext.Network()),
IsSync: ko.observable(globalContext.Sync())
};
$('#login').live('pagecreate', function (event) {
viewLoginContent = document.getElementById("loginContent");
ko.applyBindingsToNode(viewLoginContent, lVM);
viewLoginFooter= document.getElementById("footerLogin");
ko.applyBindingsToNode(viewLoginFooter, footerViewModelLogin);
});
$('#login').live('pagehide', function (event, ui) {
$.mobile.hidePageLoadingMsg();
});
function loginViewModel() {
var self = this;
try {
self.userName = ko.observable("");
self.password = ko.observable("");
self.message = ko.observable("");
self.CleanGlobalContext = function () {
...
};
self.Validate = function () {
...
};
}
catch (e) {
if (IsDebug) alert("GlobalContext.prototype.SetMapOverlay " + e.message);
if (typeof (console) != 'undefined' && console) console.log("GlobalContext.prototype.SetMapOverlay " + e.message);
}
}
ko.applyBindings(lVM);
ko.applyBindings(footerViewModelLogin);
The knockout fails without the element predefined event to bind .
I have not understood well you difficulty. However, I don't understand why you need to reapply bindings. Notice what follows:
If you change an observable array the needed templates are re-instantiated to updated coherently the UI. However you have to update the observalble array either by using the observable array functions, or by passing to the observable a new array: obs(newArray).
If you need to perform actions after the ko re-rendering you just need to use the afterRender, or afterAdd parameters of the template binding
if you add new jquery mobile code you have to parse it after having created it otherwise jquery mobile will not work...again you can do this in the afterRender function.
it is problematic to load html containing ajax ko bindings via ajax. The right approach is to create that content as a template, that you render immediately (not with ajax). Then you query the server just to get new json content. Then you can instantiate the template by using for instance the with binding.
Yes you can reapply bindings with ko.applyBindingsToNode function to the specific dom element.
Check these examples
http://jsfiddle.net/rniemeyer/gYk6f/ ---> With templating
http://jsfiddle.net/rniemeyer/BnDh6/ ---> With data - value pair
The solution was to add afterRender on the foreach table data-bind. as – Francesco Abbruzzese suggested.
The ajax request has been turned to async:false though.
Each time I update the list I perform some dat-bind = "click:updateRowList" which updates the table.
Thanks a lot to Elad Katz for help with bounty .

Resources