Simple WinJS ListView Binding - javascript

I am developing a Windows 8.1 app, and I have some data I want to bind to a listview. For some reason, I am not able to have the data shown, and I am not quite sure where I am making the mistake.
HTML:
<div id="resultTemplate" data-win-control="WinJS.Binding.Template">
<div class="win-type-small result" data-win-bind="innerText:name"></div>
</div>
<div data-win-control="WinJS.UI.ListView" id="resultsView"></div>
Javascript:
var results = [{ name: "quebec" }, { name: "quebec1" }];
var dataList = new WinJS.Binding.List(results);
var resultsListView = document.getElementById("resultsView").winControl;
var resultTemplate = document.getElementById("resultTemplate");
resultsListView.itemTemplate = resultTemplate;
resultsListView.itemDataSource = dataList.dataSource;
I am calling WinJS.UI.processAll() at the top of my javascript.

I don't see anything wrong with it, but you could try setting the itemTemplate in the html.
<div id="resultTemplate" data-win-control="WinJS.Binding.Template">
<div class="win-type-small result" data-win-bind="innerText:name"></div>
</div>
<div data-win-control="WinJS.UI.ListView" id="resultsView" data-win-options="{ itemTemplate: select('#resultTemplate')}"></div>
Notice the new data-win-options attribute in ListView tag

Related

How to make text content of a reusable navbar included in all pages to reflect

I included a reusuable navbar on multiple pages and it's working fine but when I tried changing the textContent of a word on same navbar, it shows undefined even when i have already declared the variable. What am I not getting right?
I wish to change the span with the id first_name to the name of the data.first_name in the array and I want it to reflect on every page.
$(function() {
$("#nav-placeholder").load("navbar.html");
var first_name = document.getElementById("first_name");
var data = [{
"first_name": "Chibuogwu"
}]
first_name.innerHTML = data.first_name;
});
<div class="content-side content-side-full text-center bg-black-10">
<div class="smini-hide">
<img class="img-avatar" src="assets/media/photos/avatar0.jpg" alt="">
<div class="mt-2 mb-1 font-w600">
<span id="first_name"> User</span></div>
</div>
</div>
When you use jQuery, use jQuery
Also load is async and data is an array
const data = [{
"first_name": "Chibuogwu"
}]
$(function() {
$("#nav-placeholder").load("navbar.html",function() {
$("#first_name").html(data[0].first_name);
});
});
data is an array so it should be accessed first. Please check below:
first_name.innerHTML = data[0].first_name;

set data-options html attribute

I have the following HTML
<div id="tabPanelContainer">
<div id="Tab1" data-options="dxItem: { title: 'Tab1' }">
<div id="gridContainer1"></div>
</div>
<div id="Tab2" data-options="dxItem: { title: 'Tab2' }" >
<div id="gridContainer2"></div>
</div>
</div>
I want to create this using js or jquery I have tried the following:
A.
var tabs = $('#tabPanelContainer').data("options","dxItem: { title: "+tabId+" }");
$(tabs).append('<div id='+gridId+'></div>');
B.
var tabs = $('#tabPanelContainer').attr({ 'data-options': 'dxItem: { title: "+tabId+" }' });
$(tabs).append('<div id='+gridId+'></div>');
I have looked at multiple threads on how to do this and tried multiple things but nothing is working....
I have found this: How to set data attributes in HTML elements , and other similar threads but not quite the same or enough to figure it out.
This creates multiple grids but not the tabs. So to be clear if I create the HTML elements on the PHP file (hardcoded) then my tabs load correctly but if I try to dynamically create the tabs based on a for loop my tabs don't get created.
Instead of
You are setting the data attribute of #tabPanelContainer instead of each div element. Use this code instead:
var tabs = $("#tabPanelContainer"); // <div id="tabPanelContainer">
var tab = $("<div>", { id: tabId }); // <div id="Tab1">
tab.attr("data-options", "dxItem: { title: '" + tabId + "' }");
tab.append($("<div>", { id: gridId })); // <div id="gridContainer2">
$(tabs).append(tab);

Async loading a template in a Knockout component

I'm pretty experienced with Knockout but this is my first time using components so I'm really hoping I'm missing something obvious! I'll try and simplify my use case a little to explain my issue.
I have a HTML and JS file called Index. Index.html has the data-bind for the component and Index.js has the ko.components.register call.
Index.html
<div data-bind="component: { name: CurrentComponent }"></div>
Index.js
var vm = require("SectionViewModel");
var CurrentComponent = ko.observable("section");
ko.components.register("section", {
viewModel: vm.SectionViewModel,
template: "<h3>Loading...</h3>"
});
ko.applyBindings();
I then have another HTML and JS file - Section.html and SectionViewModel.js. As you can see above, SectionViewModel is what I specify as the view model for the component.
Section.html
<div>
<span data-bind="text: Section().Name"></span>
</div>
SectionViewModel.js
var SectionViewModel = (function() {
function SectionViewModel() {
this.Section = ko.observable();
$.get("http://apiurl").done(function (data) {
this.Section(new SectionModel(data.Model)); // my data used by the view model
ko.components.get("dashboard", function() {
component.template[0] = data.View; // my html from the api
});
});
}
return SectionViewModel;
});
exports.SectionViewModel = SectionViewModel;
As part of the constructor in SectionViewModel, I make a call to my API to get all the data needed to populate my view model. This API call also returns the HTML I need to use in my template (which is basically being read from Section.html).
Obviously this constructor isn't called until I've called applyBindings, so when I get into the success handler for my API call, the template on my component is already set to my default text.
What I need to know is, is it possible for me to update this template? I've tried the following in my success handler as shown above:
ko.components.get("section", function(component) {
component.template[0] = dataFromApi.Html;
});
This does indeed replace my default text with the html returned from my API (as seen in debug tools), but this update isn't reflected in the browser.
So, basically after all that, all I'm really asking is, is there a way to update the content of your components template after binding?
I know an option to solve the above you might think of is to require the template, but I've really simplified the above and in it's full implementation, I'm not able to do this, hence why the HTML is returned by the API.
Any help greatly appreciated! I do have a working solution currently, but I really don't like the way I've had to structure the JS code to get it working so a solution to the above would be the ideal.
Thanks.
You can use a template binding inside your componente.
The normal use of the template bindign is like this:
<div data-bind="template: { name: tmplName, data: tmplData }"></div>
You can make both tmplData and tmplName observables, so you can update the bound data, and change the template. The tmplName is the id of an element whose content will be used as template. If you use this syntax you need an element with the required id, so, in your succes handler you can use something like jQuery to create a new element with the appropriate id, and then update the tmplname, so that the template content gets updated.
*THIS WILL NOT WORK:
Another option is to use the template binding in a different way:
<div data-bind="template: { nodes: tmplNodes, data: tmplData }"></div>
In this case you can supply directly the nodes to the template. I.e. make a tmplNodes observable, which is initialized with your <h3>Loading...</h3> element. And then change it to hold the nodes received from the server.
because nodesdoesn't support observables:
nodes — directly pass an array of DOM nodes to use as a template. This should be a non-observable array and note that the elements will be removed from their current parent if they have one. This option is ignored if you have also passed a nonempty value for name.
So you need to use the first option: create a new element, add it to the document DOM with a known id, and use that id as the template name. DEMO:
// Simulate service that return HTML
var dynTemplNumber = 0;
var getHtml = function() {
var deferred = $.Deferred();
var html =
'<div class="c"> \
<h3>Dynamic template ' + dynTemplNumber++ + '</h3> \
Name: <span data-bind="text: name"/> \
</div>';
setTimeout(deferred.resolve, 2000, html);
return deferred.promise();
};
var Vm = function() {
self = this;
self.tmplIdx = 0;
self.tmplName = ko.observable('tmplA');
self.tmplData = ko.observable({ name: 'Helmut', surname: 'Kaufmann'});
self.tmplNames = ko.observableArray(['tmplA','tmplB']);
self.loading = ko.observable(false);
self.createNewTemplate = function() {
// simulate AJAX call to service
self.loading(true);
getHtml().then(function(html) {
var tmplName = 'tmpl' + tmplIdx++;
var $new = $('<div>');
$new.attr('id',tmplName);
$new.html(html);
$('#tmplContainer').append($new);
self.tmplNames.push(tmplName);
self.loading(false);
self.tmplName(tmplName);
});
};
return self;
};
ko.applyBindings(Vm(), byName);
div.container { border: solid 1px black; margin: 20px 0;}
div {padding: 5px; }
.a { background-color: #FEE;}
.b { background-color: #EFE;}
.c { background-color: #EEF;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="byName" class="container">
Select template by name:
<select data-bind="{options: tmplNames, value: tmplName}"></select>
<input type="button" value="Add template"
data-bind="click: createNewTemplate"/>
<span data-bind="visible: loading">Loading new template...</span>
<div data-bind="template: {name: tmplName, data: tmplData}"></div>
</div>
<div id="tmplContainer" style="display:none">
<div id="tmplA">
<div class="a">
<h3>Template A</h3>
<span data-bind="text: name"></span> <span data-bind="text: surname"></span>
</div>
</div>
<div id="tmplB">
<div class="b">
<h3>Template B</h3>
Name: <span data-bind="text: name"/>
</div>
</div>
</div>
component.template[0] = $(data)[0]
I know this is old, but I found it trying to do the same, and the approcah helped me come up with this in my case, the template seems to be an element, not just raw html

How to dynamically bind a WinJS list view within a repeater

I have a WinJS Repeater which is using a template. That template contains a WinJS list view. I can't seem to figure out how to use data-win-bind to set the inner list views itemDataSource.
My Repeater:
<section id="genreView" aria-label="Main content" role="main">
<div id="genreWrapper">
<div id="genreRows" data-win-control="WinJS.UI.Repeater"
data-win-options="{template: select('#genreRowTemplate')}">
</div>
</div>
</section>
My Template which contains a List View:
<div id="genreRowTemplate" data-win-control="WinJS.Binding.Template">
<div id="genreRow">
<h2 class="genreTitle" data-win-bind="innerText: genreTitle"></h2>
<div class="genreMovieListView"
data-win-control="WinJS.UI.ListView"
data-win-bind="itemDataSource : data"
data-win-options="{ layout: { type: WinJS.UI.GridLayout },
itemsDraggable: false,
selectionMode: 'single',
tapBehavior: 'none',
swipeBehavior: 'none',
itemsReorderable: false,
itemTemplate: select('#genreMovieTemplate')}">
</div>
</div>
</div>
My List View's template:
<div id="genreMovieTemplate" data-win-control="WinJS.Binding.Template">
<div class="genreMovieItem">
<img style="width: 175px; height: 250px;" data-win-bind="alt: title; src: posterUrl" />
</div>
</div>
The data for the repeater is similar to this (only it's a binding list):
var repeaterData = [{genreTitle: "titleA", data: new WinJS.Binding.List() },
{genreTitle: "titleB", data: new WinJS.Binding.List() }
{genreTitle: "titleC", data: new WinJS.Binding.List() }
{genreTitle: "titleD", data: new WinJS.Binding.List() }];
The data is created on the fly and each binding list is actually a lot more data so I can't get a good sample of real data.
What I DO get is a repeated control, repeated exactly the number of times as the records in my bound list. What I DON'T get is the binding list displayed. My inner binding list is not getting databound via the data-win-bind. I've tried a few things and I either get nothing or an error. Any help is appreciated. Thanks.
EDIT: I think the right way to bind would be data-win-bind="data-win-options.itemDataSource: data", but doing that throws the following confusing error: "JavaScript runtime error: WinJS.UI.Repeater.AsynchronousRender: Top level items must render synchronously".
I was able to solve my problem, but I don't think I went about it in the right way. I went ahead and set the data source for the repeater, which gives me my genreRows from above. This was always working, it was just the child dataSource I couldn't figure out how to get to. My solution... set it in code after it loads. Nothing fancy, just a solution that feels a bit hacky to me. Here's my code in case it helps someone else get past this problem.
var titleList = $(".genreRow > .genreTitle");
var genreLists = $(".genreRow > .genreMovieListView");
for (var i = 0; i < genreLists.length; i++) {
var title = titleList[i].innerText;
var listControl = genreLists[i].winControl;
tempData.forEach(function (element, i) {
if (element.genreTitle == title)
listControl.itemDataSource = element.data.dataSource;
});
};
Basically the above code assumes the title is unique (which it is). So it uses this as a key to traverse the data and set the itemDataSource that way.
I won't mark this as the accepted answer just in case someone can point out how to do this "right".
Old question, but still deserves a good answer:
I've modified your HTML to show the correct binding syntax.
<div id="genreRowTemplate" data-win-control="WinJS.Binding.Template">
<div id="genreRow">
<h2 class="genreTitle" data-win-bind="innerText: genreTitle"></h2>
<div class="genreMovieListView"
data-win-control="WinJS.UI.ListView"
data-win-bind="winControl.itemDataSource : data.dataSource"
data-win-options="{ layout: { type: WinJS.UI.GridLayout },
itemsDraggable: false,
selectionMode: 'single',
tapBehavior: 'none',
swipeBehavior: 'none',
itemsReorderable: false,
itemTemplate: select('#genreMovieTemplate')}">
</div>
</div>
Notice the winControl.itemDataSource and data.dataSource. Any WinJS control property that is not a standard HTML element property needs the winControl property in front of whatever property you are databinding. So the onclick property of a button element doesn't need it, but WinJS.UI.Command has icon which is not on the underlying button so needs the winControl prefix.
Also, ListView controls bind to a WinJS.Binding.List's dataSource property, not the List itself. For some reason, a repeater binds to the ListView itself however.

Data binding while manipulating the DOM not working with Angular, Knockout

I am looking to implement Angular, Knockout or another to data-bind a wizard-style application form proof-of-concept (no server-side code). However I appear to be breaking the data bindings when I clone the data-bound div.
The first few steps of the application form capture data, while the later steps present the data back to the user to allow them confirm what was entered. I am manipulating the DOM by inserting the appropriate step when 'next' is pressed and taking out the last step when 'previous' is pressed. I do this using detatch, clone and remove.
Can anyone give advise on the approach they would take to make this work, and what frameworks I should look at?
Below is pseudocode to give an idea of the structure. The pseudo-data-binding-code is just how I thought it would work, I'm not bedded to any framework.
HTML View
<div id="wizard">
<div id="step1">Enter your name: <input type="text" id="name" /></div>
</div>
<div id="actions"><input type="button" value="Previous" /><input type="button" value="Next" onClick="goNext();" /></div>
<div id="steps">
<div id="stepA">Enter your age: <input type="text" id="age" databind="theAge" /></div>
<div id="stepB">The age you entered - {{ theAge }} is too young!</div>
<div id="stepC">Enter your favourite colour: <input type="text" id="faveColour" databind="faveCol" /></div>
<div id="stepD">Hi {{ name }}. You are {{ age }} years old and your favourite colour is {{ faveCol }}</div>
</div>
JavaScript
<script>
function goNext() {
// figure out which step is next
insertStepIntoWizard(step, index, title);
}
function insertStepIntoWizard(step, index, title) {
var element = step.detach();
wizard.steps('insert', index, {
title: title,
content: element.clone()
});
console.log('insertStepIntoWizard - just inserted ' + step.attr('id') + ' into wizard position ' + index);
}
</script>
I think you're thinking in terms of having your view reflect your entity model, which is basically templating. If you're looking to use Knockout/Angular, consider using it's view model to manage page state / flow / actions, in addition to controlling the entity. (Writing jQuery code to poke about with the DOM and clone, show/hide, etc is no fun). #sabithpocker makes a similar point.
Working example: I'm familiar with Knockout, and have created an example jsFiddle of your scenario: http://jsfiddle.net/overflew/BfRq8/5/
Notes:
I've used the template tag to house each section of the wizard, and all steps point to the same model/entity within the viewmodel.
To emphasise what's happening with the publish/subscribe nature of the bindings:
The user input is also relayed at the bottom of the page.
The form title is dynamic, as well as the 'step'
ko.computed is used to 'compute' the full name and if there are any 'steps' left to go
Knockout-specific: Notice the occurrence of brackets popping up around the place. This is one thing that may catch you out occasionally if you choose to learn Knockout. It just means that you're evaluating the binding container to get the value.
View model
<div>
<h3 data-bind="text: currentStep().name"></h3>
<div data-bind="template: { name: 'wizard-step1' }, visible: currentStep().id === 0"></div>
<div data-bind="template: { name: 'wizard-step2' }, visible: currentStep().id === 1"></div>
<div data-bind="template: { name: 'wizard-step3' }, visible: currentStep().id === 2"></div>
<input type="button" value="Next step" data-bind="click: onNext, visible: hasNextSteps" />
<input type="button" value="Submit" data-bind="click: onSubmit,visible: !hasNextSteps()" />
<div data-bind="visible: submitResultMessage, text: submitResultMessage"></div>
</div>
<div>
<h3>Your inputs</h3>
<div data-bind="visible: questions.fullName">Full name: <span data-bind="text: questions.fullName"></span></div>
<div data-bind="visible: questions.age">Age: <span data-bind="text: questions.age"></span>
</div>
<div data-bind="visible: questions.favouriteColour">Favourite colour: <span data-bind="text: questions.favouriteColour"></span>
</div>
</div>
<script type="text/html" id="wizard-step1">
<div>
First name: <input data-bind="value: questions.firstName, valueUpdate:'afterkeydown'" />
</div>
<div>
Last name: <input data-bind="value: questions.lastName, valueUpdate:'afterkeydown'" />
</div>
</script>
<script type="text/html" id="wizard-step2">
<div>
Age: <input data-bind="value: questions.age, valueUpdate:'afterkeydown'" />
</div>
</script>
<script type="text/html" id="wizard-step3">
<div>
Favourite colour: <input data-bind="value: questions.favouriteColour, valueUpdate:'afterkeydown'" />
</div>
</script>
View
// Entity for holding form data.
var FormData = function() {
var self = this;
self.firstName = ko.observable("");
self.lastName = ko.observable("");
self.age = ko.observable("");
self.favouriteColour = ko.observable("");
self.fullName = ko.computed(function() {
if (!self.firstName() && !self.lastName()) {
return "";
}
return self.firstName() + " " + self.lastName();
});
}
// Quick handling for managing steps of the wizard
var wizardSteps = [
{ id: 0, name: "Wizard step 1"},
{ id: 1, name: "More questions"},
{ id: 2, name: "Last step"}
];
var ViewModel = function() {
var self = this;
// Properties
self.questions = new FormData();
self.currentStep = ko.observable(wizardSteps[0]);
self.submitResultMessage = ko.observable();
// Actions
self.onNext = function() {
var currentIndex = self.currentStep().id;
if (self.hasNextSteps()) {
// Move forward one step on the wizard
self.currentStep(wizardSteps[currentIndex + 1]);
}
};
self.onSubmit = function() {
self.submitResultMessage("Data is now submitted ");
};
// Page control
self.hasNextSteps = ko.computed(function() {
var currentIndex = self.currentStep().id;
return currentIndex < wizardSteps.length - 1;
});
};
ko.applyBindings(new ViewModel());
What most of the bleeding edge javascript frameworks is trying to do is attempting to manage the huge amount of code in current applications where large amount of business logic is implemented with javascript in client side. So they are mostly trying to provide you with some architecture to organize your code to make it easy to manage, read and scale.
In your case you are trying to neglect the architecture like MVC or MVWhatever they are providing and use the framework to do some templating, If I understand you correctly. For that you can better get the help of some templating engine in javascript like handlebars and use it to manually render your data stored in your current javascript app.
see it here http://handlebarsjs.com/
Simply re-initialize your bindings.
This solves my problem when using knockout.
When you change the main DOM element which is actually being referenced for MVVM, it turn-out that any change or re-structuring that element hampers the dom relationship.
Eventually, though the placement of the item looks same but technically, in java script engine it is not. So the problem occurs.
In order to fix something like this, simply have a constructor which will initialize or re-initialize the mapping for a particular element in DOM.
Hope that solves your problem.
Example:
function ReInitializeVM()
{
ko.cleanNode(document.getElementById("userDetails"));
ko.applyBindings(viewModel, document.getElementById("userDetails"));
}
The function can be called everytime where you feel the need of re-initializing the bindings. Calling the function will remove any binding on the element with id "userDetails" and then the applyBindings can be called to initialize the binding. This will invoke bindings for any new/changed element.

Categories