Näytetään tekstit, joissa on tunniste HTML5. Näytä kaikki tekstit
Näytetään tekstit, joissa on tunniste HTML5. Näytä kaikki tekstit

25 lokakuuta, 2014

Part 4 Actual app object

How to build minimum JavaScirpt app

First our mini app needs to have private parts encapsulated so that nobody will mess around there.  Second, your app needs to have a public interface for commands so we can use it. We need to do simple model to start, so we can test it first and then we add some functinality piece by piece until it is ready. All this is possible to do with wrapper function. 

Minimum (experimental) app looks like this:

var app = (function () { // app & private area start
var secret,
privateSetter = function (x) {
alert( "validating:" + x);
secret = x;
return true;
}; // private area end
return { // privileged area start
'get': function get () { // getter
return secret;
},
'set': function set (c){ // setter
return privateSetter (c);
}
    }; // privileged area end
} () ) ; // app end

Lets go thru it part by part:

First there is variable app that contains the whole app inside it:
var app = ();

Then there is anonymous wrapper function, with again clauses that will execute it
function (){}()

Inside anonymous app function there is return {}; part which will give us two functions, get and set in an object, only they are visible outside of the object. This leaves everything else in function-object to private variables, so nobody can mess around with their values. Except get and set functions of course, that's why they are called privileged functions. PrivateSetter function will deliver the value to the private variable, so that we have important opportunity to validate it's value first. Now we just say so, actually do validate nothing, but this is the place where it happens someday near future, you know. 

Notice that this function will return true when it is ready and done. We could easily change this so that it would return the old value instead. Or something else, like a length of string or array, or anything else we need, or so that it would not return anything. 

Time to put it into test bench

So build the thing and try in browser if it works. It should.

app.set("This is my App!"); // validating:This is my App!
put(app.get()); // Message: This is my App!

Var secret is safe. If you try to read it straight from variable it will not happen. First write something into secret pocket of app, official way, with set handler.
app.set('ABRAKADABRA'); // validating:ABRAKADABRA

Then try to sneak it out, but without getter -handler.
alert("UGH:" + app.secret); 
// UGH:undefined - Oh, no... can't get it ! It is hidden !

Next  try to overwrite the value without setter -handler:
app.secret = "foo"; // There you have it, try to spell me now you...

And read it back... 
var temp = app.secret = app['secret']; // can try both ways
alert("secret:" + temp); // secret:foo 

/* What, foo?! Did I manage to overwrite it?!  
Ha, who is the man now? Mama, I rule the universe! */

... but then after a while:
/* using official get -handler: */
alert("app.get:"+ app.get()); 
// app.get:ABRAKADABRA   - Oh noooo, you fooled me ! You bastards...

What really happened here was that without the "official" setter handler, you just created (into the app -object) one more public variable with same name (secret) as original private variable, but because they actually are in different scope it is not that harmful at all. Original data was safe all the time in private area of object and if your app will only read it official way, there is no way you can go wrong here. You can store your phone number there and expect nobody to call you for a long time. Bad guys must be more clever to get your precious data now.

This is THE minimum app with JavaScript. Is there something missing?
Could we make some improvements... ? Let me know...

Learn more about strict mode on next lesson.

23 lokakuuta, 2014

Part 1 JavaScipt MiniApp HTML5

Miniapp with JavaScript

How to build modern minimum application bare bone, 
with JavaScript in  ECMA 5.1 and in the 'strict mode' ?

First you need minimum HTML 5 page and link to your .js script file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>StrictModeTestBench, ECMA5.1
    </head>
    <body>
<div id="stage">Hello World Barebone HTML 5
<!-- onerror will reveal if problem is in the file load, or url of the file  -->
        <script src="js/main.js" onerror="alert('Load Err: ' + this.src)"></script>

<!-- If your browser is using cache, use this to force load changes -->
<a href="js/main.js">Load main.js into browser
    </body>
</html>

Usually this is called "index.html", but any name will do if the suffix is right. Use always only plain text. Ok, next let's dive into JavaScript.

22 lokakuuta, 2014

Part 2 JS Workbench

Workbench for JavaScript coding in 'strict mode'

How to start coding in strict mode JavaScript. In 'strict mode' there is very much different rules than "normal" JavaScript. But it is worth of effort to learn new skills right now, especially if you just started to learn JavaScript. Always good to have external script file, do not code in HTML document at all, if you can. Make sure you have this kind of script tag in your HTML5 document:

<script src="js/main.js" onerror="alert('Load Err: ' + this.src)">

There is special onerror -handler that shall reveal if problem is already in the file load, or url of the file. You can't find the error from the file if it is not even loaded. Next, make a "main.js" -file into folder named "js" and start writing some JavaScript in it, like this example. First line is always this, and last line is always that (3rd line).

var xyz = function () { 'use strict'; // this is wrapper start ...
       // Only 'strict mode' -experiments here !
}(); // strict mode wrapper end

This is a recommendation: Use "function format" of 'use strict' -sentence.

1. First there is there clauses: (); - So everything is isolated from global window object

2. Anonymous function is next and with extra clauses it is runned into memory. 
This is a wrapper for our app.

function () {} ();

3. Next big thing, and first thing in actual code block is the 'strict mode' -message that tells the browser to be strict with everything. If you put 'strict mode' -message only inside of functions, all global area will not be in 'strict mode'. 
This is the best practise nowadays, as far as I know.

4. Next put some error codes to help with finding where the errors are hiding: 
Those alert -messages can be changed to use anything to get the messages into your debugger, if you use one.

Adding Try - cach() - finally - blocks to catch some error messages.

try {  /*debug area*/
window.onerror=function(msg,Url,Ln,ch){
alert("Window error:\n" + msg + "\nURL: " + Url + "\nLine: " + Ln+"/"+ch);
};
///////////// TEST AREA START - DO NOT EDIT BEFORE THIS ///////////

// Only 'strict mode' -experiments here !

var put = function(w) {alert('Message: ' + w ); };
put("Hello World"); // Testing 'put' -function

///////////// TEST AREA END - DO NOT EDIT AFTER THIS ///////////
 } catch (e) { //This is runned only if some error has been thrown
        throw e; //Sending error to window.onerror -handler for line number.
} finally { //This block is runned every time.
//alert("'main.js' loaded in memory."); 
 } // try

There you are. Nothing to do with actual 'strict mode' -code yet, but we are coming to it...
Next thing is to try some interesting experiments with this workbench. 
Maybe we add a little self made unit testing method and...
That will be explained on next page.