WinJS: How can I access page functions and variables from HTML? - windows-8

I'm defining page with some vars and methods. Then I wanna use it in html markup (for example data-win-bind="textContent: myPage.variable). How can I access page variables in html markup?

In the JavaScript code behind your page, say default.js, you'd include your ViewModel for the data binding, something like:
(function(){
WinJS.Namespace.define("MyModel.myPage", {
variable : null
};
MyModel.myPage.variable = 'foo';
})();
Then in when the page is activated (in default.js), you'll need to initialize the bindings with a call like
WinJS.Binding.processAll(document.body, MyModel);
There's quite a bit more functionality available though, so this is just a simplistic one-way binding case that should get you started. For more info, check out the Quickstart: binding data and styles.

You have to use javascript here's the skeleton:
<html>
<head>
<script type="text/javascript">
//Code goes here
</script>
</head>
<body>
</body>
<html>

Related

Vue components stop updating when page is translated by Google translate

When pages with Vue components are translated via chrome's translate option, the vue components stops re rendering and updating the view.
Ex: Translate https://v2.vuejs.org/v2/guide/#Handling-User-Input on chrome using the translate option from chromes's context menu into a different language, the reverse message demo stops working.
Since Google translate plugin updates DOM outside of Vue's control, this is sort of expected. Looking for any work arounds that let both co-exist. The sections can be marked with "notranslate" class but that would mean it is no longer translatable.
React inspite of being based on virtual DOM, works even with DOM being modified by translate plugin.
A possible workaround is to use the Vue special attributes key (as described here) and ref (as described here).
Here it is an example I did, starting from the link you provide above:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue.js Reverse Example</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app-5" class="demo">
<!-- Adding Vue attributes here -->
<p :key="message" ref="msg">{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
<script>
var vm = new Vue({
el: '#app-5',
data: {
message: 'Hello Vue.js!'
},
methods: {
reverseMessage: function () {
// vm.$refs.msg.innerText retrieves the translated content
this.message = vm.$refs.msg.innerText.split('').reverse().join('')
}
}
})
</script>
</body>
</html>
As you may notice, the DOM element where you'd like to maintain the Vue reactive behavior (i.e.: the reverse operation here), has been enriched with both a key attribute and a ref one.
The idea here is to use:
:key to force replacement of the element instead of reusing it;
ref to register a reference to the element: it is used in reverseMessage method in order to get the translated innerText content after the Google translation is performed.
For sure, this workaround would affect the performance, but at least it provides the expected behavior (i.e.: the reverse function properly working also after a page translation).

Handlebars with Express: different html head for different pages

I am using Handlebars in an Express Node.js app. My layout.html file includes a <head> section. How can I make the <head> section different for different pages? (So that I can, for example, reference a JavaScript file in only one page, and vary the <title> for each page.)
layout.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src='/public/ajsfile.js'></script>
<link type='text/css' href="/public/style.css" rel="stylesheet">
</head>
<body>
{{{body}}}
</body>
</html>
(I am imagining varying the <head> content with something analogous to {{{body}}} in the above, but with {{{head}}}.)
This is a great question and, in my mind, a glaring weakness in Express's view model. Fortunately, there is a solution: use Handlebars block helpers. Here's the helper I use for this purpose:
helpers: {
section: function(name, options){
if(!this._sections) this._sections = {};
this._sections[name] = options.fn(this);
return null;
}
}
Then, in your layout, you can do the following:
<head>
{{{_sections.head}}}
</head>
<body>
{{{body}}}
</body>
And in your view:
{{#section 'head'}}
<!-- stuff that goes in head...example: -->
<meta name="robots" content="noindex">
{{/section}}
<h1>Body Blah Blah</h1>
<p>This goes in page body.</p>
You can make the follow:
layout.hbs
<head>
<title>{{title}}</title>
{{#each css}}
<link rel="stylesheet" href="/css/{{this}}" />
{{/each}}
</head>
app.js
router.get('/', function (req, res, next) {
res.render('index', { title: 'MyApp', css: ['style.css', 'custom.css'] });
});
Result:
<head>
<title>MyApp</title>
<link rel="stylesheet" href="/css/style.css" />
<link rel="stylesheet" href="/css/custom.css" />
</head>
Maybe, you could use this implementation of the section helper: https://github.com/cyberxander90/express-handlebars-sections
You just need to install it and enable it:
yarn add express-handlebars-sections # or npm
const expressHandlebarsSections = require('express-handlebars-sections');
app.engine('handlebars', expressHandlebars({
section: expressHandlebarsSections()
}));
Hope it helps.
Younes
I know this is an older question but I wanted to point out a clear alternative solution to what you are asking (I'm not entirely sure why nobody else spoke about it over the years). You actually had the answer you were looking for when you bring up placing things in {{{head}}} like you do for {{{body}}}, but I guess you needed help understanding how to make it work.
It seems possible that most of the answers on this page are geared towards Node "Sections" because you speak about the different sections of HTML you've included in your layout file that you want to change. The "Sections" everyone is speaking about in this thread seems to be a technique, although I may be mistaken, originating from Microsoft's Razor Template Engine. More info: https://mobile.codeguru.com/columns/dotnet/using-sections-and-partials-to-manage-razor-views.htm
Anyway Sections work for your question, and so could "Partials" theoretically (although it may not actually be the best option for this). More info on Partials:
https://www.npmjs.com/package/express-partial
However, you simply asked for a way to alter the HTML tag content of your template layout in Handlebars, and assuming we are talking about HTML head tags, all you need to do is replace the content you have in your template layout HTML head tags with one of these (I use 3 brackets because it seems HTML would be included and you don't want it escaped):
<head>
{{{headContent}}}
</head>
Then you just dynamically pass whatever data you want through the route you create in your app.js file to "get" the page like so (I am mostly taking the code #Fabricio already provided so I didn't have to rewrite this):
router.get('/', function (req, res) {
res.render( 'index', { headContent:'I DID IT!' });
});
Now when you load your page, "I DID IT!" will be where you expect it to show up.

Declaring Variables in DOJO

I am writing a JSP that displays a list of clubs in a grid. The grid shows the name of the club together with its latitude, longitude, website and description.
The actual data to be displayed is stored in a variable (a dojo.data.ItemFileWriteStore) called clubStore.
When the page is loaded, a call is made to a servlet to retrieve the data. The handling function then deletes all the items held in the store and adds new items returned by the servlet.
The JSP code is shown below:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clubs</title>
<style type="text/css">
#import "./dojoroot/dojo/resources/dojo.css";
#import "./dojoroot/dijit/themes/tundra/tundra.css";
#import "./dojoroot/dojox/grid/resources/Grid.css";
#import "./dojoroot/dojox/grid/resources/nihiloGrid.css";
</style>
<script type="text/javascript" src="dojoroot/dojo/dojo.js"
djConfig="parseOnLoad: true, isDebug: false">
</script>
<script language="JavaScript" type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojo.data.ItemFileWriteStore");
var clubData={
items:[{name:'No Clubs', lat:'---', lon:'---', webSite:'---', description:'---'}]
};
var layoutClub=[{field:"name", name:"Name", width:10},
{field:"lat", name:"Lat", width:5},
{field:"lon", name:"Long", width:5},
{field:"webSite", name:"Web Site", width:10},
{field:"description", name:"Description", width:'auto'}];
var clubStore=new dojo.data.ItemFileWriteStore(data:clubData});
</script>
<link rel="stylesheet" href="dojoroot/dijit/themes/claro/claro.css" />
<link rel="stylesheet" href="dojoroot/dojox/widget/Dialog/Dialog.css" />
</head>
<body class="tundra">
<%#include file="header.jsp"%>
<div id="clubGrid"
style="width: 800px;"
autoHeight="true"
data-dojo-type="dojox/grid/DataGrid"
data-dojo-props="store:clubStore,
structure:layoutClub,
query:{},
queryOptions:{'deep':true},
rowsPerPage:40">
</div>
<br>
<script>
var urlString="http://localhost:8080/BasicWeb/ClubsServlet";
dojo.xhrGet({
url: urlString,
handleAs: "text",
load: function(data) {
// remove items...
var allData=clubStore._arrayOfAllItems;
for (i=0; i<allData.length; i++) {
if (allData[i]!=null) {
clubStore.deleteItem(allData[i]);
}
}
var jsonClubArray=JSON.parse(data);
for (var i=0; i<jsonClubArray.clubs.length; i++) {
var club=jsonClubArray.clubs[i];
var newClub={name: club.clubname, lat:club.lat, lon:club.lon, webSite: club.website, description: club.description};
clubStore.newItem(newClub);
}
clubStore.save();
}
});
</script>
</body>
</html>
The script to process the servlet response sometimes fails because clubStore is undefined (debugging using Firebug). This does seem to be a spurious fault as some times everything works perfectly.
Any assistance in understanding how to define the clubStore variable would be appreciated.
Thanks.
James.
I think what might be happening is the body script is sometimes running before the head script, so it is kind of a race condition. You could try wrapping your body script into a dojo.ready. (I assume from your code that you are using dojo 1.6 or earlier since you are not using the AMD loader style.)
dojo.ready(function(){
// Put your xhr request code here.
});
You may also want to try testing with a firebug breakpoint in the head and body script. See if the head is sometimes running first.
So the problem turned out to be a syntax error in the declaration - missing '{' in the line
var clubStore=new dojo.data.ItemFileWriteStore(data:clubData});
The spurious aspect to the fault was a red herring - I had previously declared the variable as part of the DOM object and that caused a spurious fault. So I messed up my regression testing as well as introducing a syntax error!
Thanks.
James.
You could try switching the order of your require statements, so it's like this:
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.parser");
If that fails, you could set parseOnLoad to false, and then call dojo.parser.parse() after your store has been instantiated like so:
(assuming you are using dojo 1.6 or earlier based on your code)
dojo.addOnLoad(function() {
dojo.parser.parse();
});
Put your clubStore in the global space... just remove the var keyword in front of it...

Using Yii's Ajax Validation without autoload Jquery

I want to use CActiveForm's AjaxValidation.
My layout view file was like this before enabling AjaxValidation:
<html lang="tr-TR" dir="ltr">
<head>
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery.js"></script>
</head>
As you see i'm calling jquery framework on my layout page (because i'm using on every page).
And i decided to use CActiveForm's ajax validation. Firstly enable enableAjaxValidation while calling it:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'otel-form',
'enableAjaxValidation'=>true,
)); ?>
And then uncomment this on my controller
$this->performAjaxValidation($model);
But i got $(...).yiiactiveform is not a function error. When i check source code of page :
As you see, one more jquery library included, too. So there are 2 jquery files on page. Because of this i'm getting error. Next i put something like this for disabling jquery.
Yii::app()->clientscript->scriptMap['jquery.js'] = false;
Now jquery is loading only once. But this result is :
<html lang="tr-TR" dir="ltr">
<head>
<script type="text/javascript" src="/istanbulcityhotels/assets/cb2686c8/jquery.yiiactiveform.js"></script>
<script src="/istanbulcityhotels/js/jquery.js"></script>
</head>
jquery.yiiactiveform.js calling BEFORE jquery.js . It should called AFTER jquery.js.
It confused a bit. What should i do?
ADDITIONAL
Yes, i read this question because titles' are really similar, but question isnot same.
Thank you.
You should not be including jQuery manually from your layout. Instead of doing this, include it from within your Controller base class:
public function init() {
Yii::app()->clientScript->registerCoreScript('jquery');
}
Don't forget to call parent::init() from within your concrete controllers.
It seems CActiveForm inserts the scripts before the title tag using CClientScript::POS_HEAD constant. So a workaround is to add this code
<?php
$cs=Yii::app()->clientScript;
$cs->scriptMap=array(
'jquery.js'=>false
);?>
to the top of the main layout file in order stop it from loading jquery, then put the title tag after you load your jquery file
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery.js"></script>
This way jquery.yiiactiveform.js will be loaded right after jquery.
just put your own jquery on tag title,
just like this:
<script src="/istanbulcityhotels/js/jquery.js"></script>
<title>your title</title>

"Container is not defined" Google chart

I have solved my issue but can't answer it myself since I am too new to this site:
turns out I needed to use the following:
chart = new google.visualization.PieChart(document.getElementById('pie_today_div'));
I was using JQuery to access the element, $('#pie_today_div'). As of now the evidence points to the fact that the PieChart constructor has to have standard JS code, document.getElementById('pie_today_div')
Maybe something else going on, but changing the way I access the container element fixes my code
ORIGINAL ISSUE FOR REFERENCE TO MY SOLUTION
I am getting a "Container is not defined" error when I am trying to instantiate a Google PieChart object.
I validated my page at http://validator.w3.org/ and i get a pretty green banner saying it validates.
I receive no js errors when the page loads. My Ajax call is making a full round trip with the data I want from the DB.
Here is my HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link href="/css/note.css?10022012" rel="stylesheet" type="text/css" media="screen">
<script type="text/javascript" language="javascript" src="/call/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.0', {'packages':['corechart']});</script>
<script type="text/javascript" language="javascript" src="/call/js/init.js?10042012-2"></script>
<title>Call Stats</title>
</head>
<body>
Today Stats
<div id="pie_today_div"></div>
</body>
</html>
here is the js:
function drawPieChartToday() {
$.post('/call/ajax.php5',{
action:'pieToday'
}, function(ticketData) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Count');
data.addColumn('number', 'Topic');
for (var key in ticketData){
data.addRow([key, ticketData[key]]);
}
options = {
title: 'Issue Topics'
};
alert($('#pie_today_div').attr('id'));
chart = new google.visualization.PieChart($('#pie_today_div'));
chart.draw(data, options);
},'json');
}
here is my debugging code to make sure the element was being found:
alert($('#pie_today_div').attr('id')); <-- alerts "pie_today_div"
I'm not a jquery fan, but I think that $('#pie_today_div') returns a set of matched elements. The attribute computation works because (from jquery documentation) it "gets the value of an attribute for the first element in the set of matched elements".
So try
chart = new google.visualization.PieChart($('#pie_today_div')[0]);
or directly
chart = new google.visualization.PieChart(document.getElementById('pie_today_div'));
A container error is exactly that, It is looking for the ID
example:
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
You WILL get this error “Container is not defined” for Google Charts if you are missing
that ID
Thus a Div with that chart_div id would fix this
There must be line where you load the types of visualization you want to have in your web page. It looks like this
google.load("visualization", "1", {packages: ["corechart"]});
Here I am loading package corechart. Place this line as the first line after in the <script> tag inside your HTML page like index.html. That should solve he problem.
use $timeout before init, it works well, else you need to destroy the instance
Just wanted to mention, this happened for me after a simple mistake. I changed
var data = new google.visualization.DataTable(huh);
to the following in an effort to change the chart type:
var data = new google.visualization.BarChart(huh);
but this is all wrong, you change the chart where you mention the container:
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));