Windows 8/ Metro UI data-binding javascript - javascript

I am creating an application using javascript/HTML for windows 8 which basically displays text which is pulled from an html file.
I am using the data.js file to organise groups and items. One of the properties is the 'url' which stores the url of the html page which contains the main content for the application.
I came up with this code to retrieve the html code from the html page which contains the content to be displayed:
WinJS.UI.Fragments.renderCopy(url)
.done(function (fragment) {
return fragment;
});
How do I run this code for each item in the array in data.js and bind the data so that the content is from the HTML page, and the headings/titles are from the data.js file?
I apologise if I'm causing any confusion. I would appreciate any help.
Thanks.

Assuming you want to stick with the layout of data.js and not create your own data classes, I would use a custom renderer for the listview.
Something like this...
var customRender = WinJS.Utilities.markSupportedForProcessing(function (itemPromise) {
var currentItem = {};
return itemPromise.then(function (item) {
currentItem = item;
var myDiv = document.createElement("div");
return WinJS.UI.Fragments.renderCopy("/html/1_BasicFragmentLoad_Fragment.html", myDiv)
})
.then(function (fragment) {
var itemTemplate = WinJS.Utilities.query('.itemtemplate')[0];
currentItem.data.title = fragment.innerHTML;
return itemTemplate.winControl.render(currentItem.data);
});
}
);
In this example, I am binding the content of a html fragment to the title of a given item from data.js. You will need to update the itemtemplate and bind the title element to innerHTML instead of textContent.
<h4 class="item-title" data-win-bind="innerHTML: title"></h4>
You will also need to assign the custom renderer to the listview. You can do this in the HTML markup or just change the template js in groupItems.js to this...
listView.itemTemplate = customRender;
If you were to create your own data classes, you may want to put the promise chain from the customer renderer into the class constructor, eliminating the need for a customer renderer.

Related

Jquery <<S.fn.init [selector]>> in Java Script Vanilla

For this project, I want to change the logic written in jquery with that in js vanilla.
My code looks like this
Based on the information from the input using the event keydown,
I call a function through which I do a search in api.
var selectedUsers = [] //empty array
$('#userSearchTextbox').keydown((event)=>{
var textBox = $(event.target);
var value = textBox.val();
//Function which search in api
searchUsers(value);
});
//Search in array function
function searchUsers(searchTerm){
$.get("/api/users",{search:searchTerm},results =>{
outputSelectableUsers(results,$('.resultsContainer'));
});
}
After I call another function outputSelectableUsers
which will call 2 functions one that displays the data in HTML and one that creates an array of values.
function outputSelectableUsers(results,container){
results.forEach(results => {
//Call function which will render the html
var html =createUserHtml(results,false);
/*
Here is the problem, as seen using jquery element variable selects html variable which render function
*/
var element = $(html);
/*
with jquery, I managed to select the variable and assign it a click event that when I click it calls the function that adapts the array with data
from each API call
*/
element.click(()=>userSelected(results))
//append content to the html selector
container.append(element);
});
}
//Function which will update the array
function userSelected(user){
selectedUsers.push(user);
}
This is what the visible result looks like
And when I click on one of the cards, the area adapts to the user's values.
values ​​that I take from the array and enter them in the database.
I managed to convert everything to js using fetch instead of ajax jquery and changed the selectors and events with vanilla js code.
But the problem is I couldn't find a way to change this piece of code.
var html =createUserHtml(results,false);
var element = $(html);
console.log(element)
element.click(()=>userSelected(results))
container.append(element);
at consol.log (element) I observed asata in the console.
The question is could I choose the element with js vanilla and get the same result as in the jquery version. To use Js Vanilla code instead of
var element = $(html);
element.click(()=>userSelected(results))
let users_id = results._id;
let html = createUserHtml(results,users_id ,false);
container.insertAdjacentHTML('beforeend',html);
//Identify each element by a unique selector
document.querySelector(`[data-selectorTab ="${results._id}"]`).addEventListener('click',()=>{
userSelected(res)
})
I solve this by adding a data attribute to dinamically generated elements,using this data atribute I can make a individual selector for each user.

ArcGIS JS API - Conditional logic within popup

I have created a custom popup with the popupTemplate function with ArcGIS JS API 4.x
It would be great to introduce some conditional logic into my popups. For example, I am currently displaying a hyperlink to a website driven by an attribute within my layer. Not all features have associated websites, so ideally the conditional logic would only display text if the URL attribute was populated. The code below shows i) my existing popup and ii) how I am guessing I would insert a conditional value.
var template = {
content: [
{
type: "text", // TextContentElement
text: "<h1><font color='#c94600'>Click <a href={URL} target='_blank'><b>here</b></a> for video </font></h1>"
},
{
type: "text", // TextContentElement
text: conditionalFunction
},
]};
where conditionalFunction = something to the effect of...
if URL.attribute not null:
> return URL
else:
> return null
Can this be done easily with simple/basic Javascript?? (i'm very much a beginner)? If I can get this working, the next step would be to show a conditional table :)
Any help much appreciated.
You have a couple of ways to do this, you can use functions or promises. Basically instead of defining the content in a "static" manner, you do it "dynamic". In this way each time the popup display the content will be generated using the feature data.
Take a look at this example of ArcGIS. It uses function to set the content of the template, and it dinamically define the arrow style to display (up or down and color).
You can do something similar, like this,
var template = {
content: function(feature) {
var div = document.createElement("div");
if (feature.graphic.attributes.URL) {
div.innerHTML =
"<h1><font color='#c94600'>Click <a href=" +
feature.graphic.attributes.URL +
" target='_blank'><b>here</b></a> for video </font></h1>";
}
return div;
},
outFields: ["URL"]
};
I am assuming that URL is the attribute that contains the url.

How to store and get data from a json file with javascript?

I would like to create a little kind of CMS. For that I want to code a function, which automatically creates a list of the files, which were created with the CMS. This list sould be display in a html file and styled with CSS. For that I want to create a json-File, in which i store the title and the location of the new file.
Then it should look like this:
{
"new_sites":
{
"title": "source",
"otherTitle": "otherSource"
}
}
Now I want to know, how I can get (or store new) data from the json-File and use it as variables in javascript so that I can display it on the html page.
Given these three variables:
var myNewSite = 'newSite';
var myNewTitle = 'newTitle';
var myNewSource = 'newSource';
and your final json variable initialized in this way:
var myJson = {};
You could simply:
myJson[myNewSite] = {
myNewTitle: myNewSource
};
You can use Jquery api to get data from json-file.Suppose you have a data.json file in directory.
<script>
var container={};
$.getJSON('data.json', function(data) {
container=data;
});
</script>

I can't change dom from dom element stored as an attribute

I Apologize if there is already an answer, I found nothing usefull.
I am developing a little JS code with some blocks that need to change their html code.
So I have a main object with 2 kinds of attributes :
custom objects with a getHtml() method
dom elements that are initialized with a id tag then should be changed.
My first version worked : i set some javascript event and methods, then my block content was changed.
Of course (!) I needed to modify the code to implements new features and now my method return html code but .innerHTML on my variables does not work anymore.
Let me show you some code and explain it
var AtelierScreen = function(ancre, dataJson){
if(!ancre.charAt) throw "Invalid string-dealer name type ('"+ancre+"') should be String";
if(ancre.length==0) throw "Invalid string-dealer name ('"+ancre+"') cannot be empty";
this.atelierContent;
this.operationMenu;
this.operationMenuContent;
this.operationRecap;
this.operationRecapContent;
this.create=function(obj,tagsuffix){
var tag = ancre+tagsuffix;
this.atelierContent.innerHTML += "<div id='"+tag+"'></div>";
var content = document.getElementById(tag);
if(!content) throw "Invalid html anchor using '"+tag+"' as an html id";
content.innerHTML=obj.getHtml();
return content;
}
try{
var dataObject = JSON.parse(dataJson);
this.atelierContent = document.getElementById(ancre);
if(!this.atelierContent) throw "Invalid html anchor using '"+ancre+"' as an html id";
// MENU
this.operationMenu = new OperationMenu(dataObject["dealer"],dataObject["operations"]);
this.operationMenuContent=this.create(this.operationMenu,"_menu");
this.operationMenuContent.innerHTML+="after init";
// RECAP
this.operationRecap = new OperationRecap();
this.operationRecapContent=this.create(this.operationRecap,"_recap");
this.operationMenuContent.innerHTML+="after recap init";
} catch(error){
throw "Error decoding json data :\n'"+error+"'\n\nJson =\n'"+dataJson+"'";
}
this.setSelectedModel=function(model){
this.operationMenuContent.innerHTML+="setSelectedModel";
var isTheSame = this.operationMenu.setSelectedModel(model);
if(!isTheSame) this.clearOperationItemFromRecap();
var temp = this.operationMenu.getHtml()
this.operationMenuContent.innerHTML=temp;
}
}
Quick overview
all my attributes and a method to help initializing them.
a try catch to check the json data.
I initialize my attributes with the method
some methods to interact with the program
Here is what happen
Json in parsed correctly
My 1st block is created, return its html code that is put in the 1st content attribute. I add some text again into the dom as a test (it works)
My 2nd block is created, return its html code that is put in the 2nd content attribute. I add some text again in the 1st content attribute as a test. It fail at this point.
my methods does not help in any way. My content attribute does not seem to respond.
I can still get the content attribute value
atelierScreen.operationMenuContent.innerHTML;
But I cannot insert text in dom.
atelierScreen.operationMenuContent.innerHTML="";
does nothing.
Do I need to query the dom with document.getElement ... EACH TIME ?
My previous version with dom elements as attributes was working...
I am missing something, this is so frustrating ;)
Please help.
Thanks
After some research, it could be because of using innerHTML.
It looks like using innerHTML destroy the child elements.
I need to work on this first but I will try something like :
create Block "abstract" parent class with tag and content parameter, constructor with tag
prototype getContent() will look like :
if(content==null) content = document.getElementById(this.tag);
return content;
initialize my main "screen" object with an array of my objects
loop on array to get tag and initialize innerHTML
loop on array to instantiate objects
getContent will handle the rest.
I will give you some feedback
Ok, this is what i did
var AtelierScreen = function(ancre, dataJson){
try{
var dataObject = JSON.parse(dataJson);
this.atelierContent = document.getElementById(ancre);
if(!this.atelierContent) throw "Invalid html anchor using '"+ancre+"' as an html id";
var blocks = [
this.operationMenu = new OperationMenu(...),
this.operationRecap = new OperationRecap(...),
this.operationResult = new OperationResult(...)
];
for (var i = 0; i < blocks.length; i++) {
var block=blocks[i];
this.atelierContent.innerHTML += "<div id='"+block.tag+"'></id>";
}
for (var i = 0; i < blocks.length; i++) {
var block=blocks[i];
block.getContent().innerHTML = block.getHtml();
}
} catch(error){
throw "Error decoding json data :\n'"+error+"'\n\nJson =\n'"+dataJson+"'";
}
}
I parse Json parameter inside try/catch
I create the screen element, that will be used to initialize my anchors
I create my array of blocks and initialize my objects in the same time (i wasn't sure it would work, if those attributes would be found later, but it does). Onjects contains their anchors and content parameter.
1st loop to add blocks anchors
2nd loop to create html content

Accessing objects/rows created in ASP.NET from Javascript

I create a table dynamically and add rows, labels etc to it.
I want to be able to access those rows to make either visible or hidden AND access labels to change content on the fly. So far the table and all info is created with no problem. I spent days trying to access the data from JS, but I keep getting NULL etc on objects using ALERT to test it. Here's a snippet example of my code...
ASP.NET (C#) code
mTable = new HtmlTable();
mTable.ID = "mTable";
aCell = new HtmlTableCell();
aLabel = new Label();
aLabel.ID = "aLabel";
aLabel.Text = "TEST";
aCell.Controls.Add(aLabel);
aRow = new HtmlTableRow();
aRow.ID = "r" + x;
aRow.Cells.Add(aCell);
mTable.Controls.Add(aRow);
Ive put the following code in a SCRIPT FILE etc and ive tried many styles.
alert(document.getElementById('<%=aLabel.ClientID%>'));
If you are using plain vanilla javascript, please look at the code sample here: How do I iterate through table rows and cells in javascript?
The code sample in the above link gets the table by id, which in your case is 'mTable' (from your c# code)
var table = document.getElementById('mTable');
// will return you a reference to the table object on the page
You also have to place the code to call your javascript function that accesses data on the 'mTable' on the document load event

Categories

Resources