<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>javascript Archives - Creatronix</title>
	<atom:link href="https://creatronix.de/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://creatronix.de/tag/javascript/</link>
	<description>My adventures in code &#38; business</description>
	<lastBuildDate>Mon, 18 Jul 2022 08:11:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.1</generator>
	<item>
		<title>ES6: var vs let vs const</title>
		<link>https://creatronix.de/es6-var-vs-let-vs-const/</link>
		
		<dc:creator><![CDATA[Jörn]]></dc:creator>
		<pubDate>Fri, 18 Aug 2017 19:57:49 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ES6]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://creatronix.de/?p=988</guid>

					<description><![CDATA[<p>Dealing with KnockoutJS I came across some newer features of the JavaScript language ES6 TL;DR: don&#8217;t use var anymore when You declare variables. Some examples: As You can see a variable declared with the var keyword is visible outside its enclosing scope. Most of the time it&#8217;s not what You want. When You enable ES6&#8230;</p>
<p>The post <a href="https://creatronix.de/es6-var-vs-let-vs-const/">ES6: var vs let vs const</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Dealing with KnockoutJS I came across some newer features of the JavaScript language ES6</p>
<p>TL;DR: don&#8217;t use <strong>var</strong> anymore when You declare variables.</p>
<p>Some examples:</p>
<p><span id="more-988"></span><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-996" src="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.41.png" alt="" width="399" height="481" srcset="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.41.png 399w, https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.41-249x300.png 249w" sizes="(max-width: 399px) 100vw, 399px" /></p>
<p>As You can see a variable declared with the <strong>var</strong> keyword is visible outside its enclosing scope. Most of the time it&#8217;s not what You want.</p>
<p>When You enable ES6 support in PyCharm it already warns You if You use <strong>var:</strong></p>
<p><img decoding="async" class="alignnone size-full wp-image-997" src="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.56.png" alt="" width="521" height="182" srcset="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.56.png 521w, https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.42.56-300x105.png 300w" sizes="(max-width: 521px) 100vw, 521px" /></p>
<p>To declared a variable which is on visible in its scope You can either use let or const.</p>
<p><img decoding="async" class="alignnone size-full wp-image-998" src="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.53.04.png" alt="" width="480" height="180" srcset="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.53.04.png 480w, https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.53.04-300x113.png 300w" sizes="(max-width: 480px) 100vw, 480px" /></p>
<p><strong>Let</strong> lets your variable be mutable so you can use it in a loop as counter. If You want to guarantee even more that one variable is used for one concept only You can use <strong>const</strong> which makes the variable immutable.</p>
<p><img decoding="async" class="alignnone size-full wp-image-999" src="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.43.27.png" alt="" width="489" height="153" srcset="https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.43.27.png 489w, https://creatronix.de/wp-content/uploads/2017/08/Bildschirmfoto-2017-08-18-um-21.43.27-300x94.png 300w" sizes="(max-width: 489px) 100vw, 489px" /></p>
<p>&nbsp;</p>
<p>The post <a href="https://creatronix.de/es6-var-vs-let-vs-const/">ES6: var vs let vs const</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Lint your JavaScript with grunt and jshint</title>
		<link>https://creatronix.de/lint-your-javascript-with-grunt-and-jshint/</link>
		
		<dc:creator><![CDATA[Jörn]]></dc:creator>
		<pubDate>Tue, 08 Aug 2017 08:30:58 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[grunt]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Jenkins]]></category>
		<category><![CDATA[jshint]]></category>
		<category><![CDATA[yarn]]></category>
		<guid isPermaLink="false">http://creatronix.de/?p=948</guid>

					<description><![CDATA[<p>After I&#8217;ve introduced You to Yarn I will show You more client side tools in this post. Grunt is a task runner which comes in handy for a lot of setup and configuring work e.g. concatenating and minimizing JavaScript or CSS files To get started You can add grunt via yarn to your project yarn&#8230;</p>
<p>The post <a href="https://creatronix.de/lint-your-javascript-with-grunt-and-jshint/">Lint your JavaScript with grunt and jshint</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>After I&#8217;ve introduced You to <a href="https://creatronix.de/yarn-package-manager/">Yarn</a> I will show You more client side tools in this post.</p>
<p><a href="https://gruntjs.com/">Grunt </a>is a task runner which comes in handy for a lot of setup and configuring work e.g. concatenating and minimizing JavaScript or CSS files</p>
<p>To get started You can add grunt via yarn to your project</p>
<pre>yarn add grunt</pre>
<h2>Configuration</h2>
<p>Grunt looks for a Gruntfile.js file in your root directory. Yes it is Gruntfile.js with a capital &#8216;G&#8217;.</p>
<h2>Linting with JShint</h2>
<pre>yarn add grunt-contrib-jshint</pre>
<pre>module.exports = function(grunt) {
  grunt.initConfig({
    jshint: {
      all: ['Gruntfile.js', '/js/*.js'],
      options: {
        globals: {
          jQuery: true
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('lint', ['jshint']);
};</pre>
<p>This configuration will print all findings directly onto the console which is nice for testing the script but when you burn down your lint issues a file comes in handy.</p>
<h2>Configuring JSHint&#8217;s Output Format</h2>
<p>To visualize the findings in Jenkins you can configure the checkstyle format. It produces an XML file which you can use inside Jenkins&#8217; checkstyle plugin.</p>
<p>When You want to have a more human readable format you can generate an html report. Therefore You have to install the jshint-html-reporter:</p>
<pre>yarn add jshint-html-reporter</pre>
<p>and configure the JSHint task accordingly.</p>
<pre>options: {
   reporter: require('jshint-html-reporter'),
   reporterOutput: 'jshint.html'
 },</pre>
<p>You can have both configurations in one file</p>
<pre>module.exports = function(grunt) {

  grunt.initConfig({
    jshint: {
      options: {
        globals: {
          jQuery: true
        }
      },
      src_files: ['Gruntfile.js', 'app/static/js/*.js'],
      local: {
        options: {
          reporter: require('jshint-html-reporter'),
          reporterOutput: 'jshint.html'
        },
        src: [ "&lt;%= jshint.src_files %&gt;" ]
      },
      jenkins: {
        options: {
            reporter: 'checkstyle',
            reporterOutput: 'jshint.xml'
        },
        src: [ "&lt;%= jshint.src_files %&gt;" ]
    }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('lint', ['jshint:jenkins']);
  grunt.registerTask('lint-local', ['jshint:local']);
};</pre>
<p>&nbsp;</p>
<p>The post <a href="https://creatronix.de/lint-your-javascript-with-grunt-and-jshint/">Lint your JavaScript with grunt and jshint</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Bringing AJAX to Flask</title>
		<link>https://creatronix.de/bringing-ajax-to-flask/</link>
		
		<dc:creator><![CDATA[Jörn]]></dc:creator>
		<pubDate>Fri, 20 Jan 2017 12:29:47 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[wsgi]]></category>
		<guid isPermaLink="false">http://creatronix.de/?p=385</guid>

					<description><![CDATA[<p>Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds. from flask import Flask # 1 app = Flask(__name__) # 2 @app.route('/') # 3 def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() #4 All this snippet does is&#8230;</p>
<p>The post <a href="https://creatronix.de/bringing-ajax-to-flask/">Bringing AJAX to Flask</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds.</p>
<pre>from flask import Flask # 1
 
app = Flask(__name__)   # 2

@app.route('/')         # 3
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()           #4</pre>
<p>All this snippet does is</p>
<ol>
<li>Importing the Flask module,</li>
<li>Creating the app,</li>
<li>Defining an so called endpoint and finally</li>
<li>Running the web app in a container.</li>
</ol>
<p>Flask brings its own WSGI server called &#8220;werkzeug&#8221;. Please use it just for development purposes. It is not suitable for live applications.</p>
<h2>Rendering a Template</h2>
<p>Because the days of writing HTML as strings in a servlet are over, Flask comes with a template language called &#8220;Jinja2&#8221;. We replace the line</p>
<pre>return 'Hello World!'</pre>
<p>with the render_template function and pass a template and the message into the function:</p>
<pre>from flask import render_template
... 
@app.route('/') 
def hello_world(): 
    hello_string = "Hello World"
    <strong>return render_template("index.html", 
                           hello_message=hello_string)</strong></pre>
<p>Jinja2 uses curly brackets to identify their template code blocks.</p>
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
<strong>{{ hello_message }}</strong>
&lt;/body&gt;
&lt;/html&gt;</pre>
<pre>{{ hello_message }} # is equivalent to
{% print hello_message %}</pre>
<p>So if You want to show a list on your page containing your favorite fruits You can fetch a list of fruits from the server and let the template engine replace the markup with the data before handing the rendered page to the browser. We use a simple list for demonstration.</p>
<pre>@app.route('/static_item_list')
def static_item_list():
    fruits = ["Apple", "Banana", "Lemon"]
    return render_template("static_item_list.html", 
                           fruits=fruits)</pre>
<pre>&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Fruit&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  {% for fruit in fruits %}
     &lt;tr&gt;
       &lt;td&gt;{{ fruit }}&lt;/td&gt;
      &lt;/tr&gt;
   {% endfor %}
   &lt;/tbody&gt;
&lt;/table&gt;</pre>
<h2>Bringing AJAX to Flask</h2>
<p><img decoding="async" class="alignnone size-full wp-image-4475" src="https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax.png" alt="" width="364" height="365" srcset="https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax.png 364w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-300x300.png 300w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-150x150.png 150w, https://creatronix.de/wp-content/uploads/2017/01/sequence_chart_ajax-100x100.png 100w" sizes="(max-width: 364px) 100vw, 364px" /><br />
When we wanted to filter a list back in the old days, we had to do a complete roundtrip by sending a POST with parameters to the server, waiting for the response and rendering a new page. Ugh! In Flask it looks like this:</p>
<pre>&lt;<strong>form</strong> <strong>method="POST"</strong>&gt;
&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Fruit&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;input <strong>name="filter"</strong>/&gt;
                <strong>&lt;button&gt;Search&lt;/button&gt;</strong>
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        {% for fruit in fruits %}
            &lt;tr&gt;
                &lt;td&gt;{{ fruit }}&lt;/td&gt;
            &lt;/tr&gt;
        {% endfor %}
    &lt;/tbody&gt;
&lt;/table&gt;
&lt;/form&gt;</pre>
<pre>@app.route('/item_list_with_filter', methods=["GET", "POST"])
def item_list_with_filter():
    fruits = ["Apple", "Banana", "Lemon"]
    
    if "filter" in request.form:
        fruit_filter_value = request.form["filter"]
    else:
        fruit_filter_value = ""

    filtered_items = []
    for fruit in fruits:
        if fruit_filter_value.lower() in fruit.lower():
            filtered_items.append(fruit)

    return render_template("item_list_with_filter.html",
                           fruits=filtered_items)</pre>
<p>Nowadays You can just refresh those parts of a site where the data should be updated. I will demonstrate this with some jQuery functionality, but You can do it as well in plain old vanilla JavaScript.</p>
<p>This is the udpated HTML page. Please note that the table body is empty and does not contain template language code.</p>
<pre>&lt;table id="items"&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Fruit&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;input id="filter"/&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;</pre>
<p>First of all we bind a keyup event to the filter input. To ensure that the complete page is already loaded, we do it in the document-ready function:</p>
<pre>$(document).ready(function(){
...
    $("#filter").keyup(get_table_data); 
...
});</pre>
<p>To fetch data from the server we use the getJSON-function.</p>
<pre class="result notranslate"><i>$</i>.getJSON( url, [data], [callback] )</pre>
<p>This function is a shortcut for</p>
<pre>$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});
</pre>
<p>As URL we have to provide an endpoint that accepts GET requests, as data we give the value from the input field and last but not least as callback a function that will use the data from the response to update the table.</p>
<pre>function get_table_data(){
    $.getJSON('/_items', {
        filter: $("#filter").val()
        }, function(data){update_table.call(this, data)}
    )
}</pre>
<p>Let&#8217;s have a look at the before mentioned endpoint:</p>
<pre>@app.route('/_items')
def items():
    <strong>filter_value = request.args.get('filter', "", type=str)</strong>
    fruits = ["Apple", "Banana", "Lemon"]

    filtered_items = []
    for fruit in fruits:
        if filter_value.lower() in fruit.lower():
            filtered_items.append(fruit)

    <strong>return jsonify(fruits=filtered_items)</strong></pre>
<p>There are two interesting parts here: To get the arguments from the request we use</p>
<pre>request.args.get()</pre>
<p>The get method takes the argument name, a default value and a type. Instead of returning a rendered template we use the method</p>
<pre>jsonify<strong>()</strong></pre>
<p>That&#8217;s all it takes to get JSON data from a Flask application. The missing piece is the function which alters the content on the client side after receiving the data. It looks like this</p>
<pre>function update_table (data) {
    var $tbody = $("#items").find("tbody");
    $tbody.empty();
    var rows = data.fruits.length;
    for (var i = 0; i &lt; rows; i++) {
        var row = "&lt;tr&gt;&lt;td&gt;" + data.fruits[i] + "&lt;/td&gt;&lt;/tr&gt;";
        $tbody.append(row);
    }
}</pre>
<p>This function clears the body of the table via empty(), iterates over the data and appends the new rows to the table body.  and Bob&#8217;s your uncle!</p>
<p>The post <a href="https://creatronix.de/bringing-ajax-to-flask/">Bringing AJAX to Flask</a> appeared first on <a href="https://creatronix.de">Creatronix</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
