Suppose I have a variable in my Javascript Module called test
const test = 'abc';
Now can I use {test} to refer to test in my html code. Or do I always have to get the html tag by document.... and them setInnerHTML to it. I would prefer if someone could give an elaborate answer to referring variables of ES6 inside HTML.
Thank you
HTML can include JavaScript only in <script> elements and intrinsic event attributes.
New versions of JavaScript do not and cannot change this. (Since it is a (non-)feature of HTML, not of JS).
The syntax you describe is used by a number of template languages, such as Nunjucks and Handlebars, along with things that are not-quite-templates like JSX. It is not HTML.
Related
I try to use JavaScript processor steps in StreamSets.
I defined some environment values and can invoke from expression.
${type}='month';
In JavaScript, how to use those environment values?
Can you write a js example for get the value of ${type} in JavaScript in StreamSets?
You reference the variable in the same way in JavaScript - EL expression evaluation is performed on the script before it is run. Note that you will need quotes for strings - for example:
var myType = '${type}';
This also works with the Jython evaluator, but it does NOT work from Groovy due to a clash with the Groovy ${} syntax.
Context: I have written a mini JS library for myself which is simply a collection of commonly used classes. I have followed the IIFE (http://benalman.com/news/2010/11/immediately-invoked-function-expression/) technique to separate my code into modules/classes and they're all grouped under a common global namespace var. Let's call it, ns. So we have a typical setup, ns.ClassA, ns.ClassB, etc. Now on the other hand, a separate script (main.js) is loaded at runtime and appended to the document, and this main.js contains the actual code that uses these classes.
Goal: I am trying to find an elegant way of accessing the classes inside main.js directly by calling the class name instead of having to access them through ns. . For example, I would want to be able to do var a = new ClassA(); instead of var a = new ns.ClassA();
Solutions researched & considered:
1) the dreaded 'with' keyword (javascript "static imports"). In this case, I would do something like with(ns){ var a = new ClassA()} , except I will have to wrap the entire main.js inside the with(ns) statement. This is undesirable for obvious reasons.
2) using locally declared variables.
var ClassA = ns.ClassA, ClassB = ns.ClassB;
and then, I will be able to instantiate ClassA and ClassB directly. However, this approach would require me to manually maintain the declaration, and it will just get very messy and hard to maintain as the number of classes increase in the package.
3) pollute the global scope by injection
use a for loop to iterate over ns and map all the classes inside nsto global scope. This is clearly undesirable, and also it will create conflicts for cases such as ns.Event, ns.Audio etc.
4) PaperScript-style (http://paperjs.org/tutorials/getting-started/working-with-paper-js/)
Inspired by PaperScript from PaperJS, where PaperScript code is automatically executed in its own scope that without polluting with the global scope still has access to all the global browser objects and functions, such as document or window. Looking at their source code on GitHub (sorry SO won't let me post any more links), they seem to be using some custom script pre-processing and then Acorn.js to parse. The end result is that one can directly refer to any class inside the paper object. For example, var path = new Path() instead of var path = new paper.Path(), which is exactly what I wanted to achieve. However, my fear is that it might seem to be too much work to implement such a simple feature. So I wanted to see if any one has any ideas?
Thank you for taking your time to read this verbose description of the problem. Any inputs are appreciated.
Note: I have done my best in the past two days into researching this topic, please forgive me if I missed any obvious solutions. In addition, if there's no easy solution to this, I will simply stick with the ns.ClassA pattern. Thank you for your help!
I'm not an expert but I believe you could create a prototype of String and set your vars like so
String.prototype.ns = function(){
return new ns[this]();
}
var ca = "ClassA".ns();
I've built a plugin that will use modules. Basically functions that can be added to the code in order to provide additional functionality.
In the plugin is a function to call these modules. Previously, I had called them like this:
processInstance($(doc).find('[data-bcp-crumbs]'), crumbs);
processInstance($(doc).find('[data-bcp-copyright]'), copyright);
processInstance($(doc).find('[data-bcp-activenav]'), activeNav);
The last part of each line is the name of a function that will be called within the processInstance script. So, I have the name of the function as both a string and a first-class object on each line. I would like to simplify that to something like this:
for (var i=0; i>module.length;i++) {
processInstance($(doc).find('[data-bcp-'+module[i].toLowerCase()+']'), window[module[i]]);
}
The module array is added to after each instance of the actual module code. I'm doing that like this:
module.push('crumbs');
This doesn't work because window[module[i]] is returning undefined.
How does my code need to be modified to make this work?
Here is an jsfiddle example of the entire plugin with a simple module inserted: http://jsfiddle.net/michaeljimmy/U8anp/1/
A colleague of mine helped me find the answer to this question. First, though, I noticed an error in the for loop. I had > instead of <. That didn't help. :)
The concept with the code was correct. The issue was scope. If you look at the jsfiddle, you'll see that the whole thing is in an enclosure, including the functions I was trying to call. So, there was no way window had access to the functions. We ended up making a couple simple changes.
First, along with module.push('crumbs'), or whatever the function name is, we added:
functions.crumbs = crumbs;
Then instead of using window[module[i]], we used
functions[module[i]]
Without the enclosure, window[module[i]] would have worked just fine.
I read a book called "Javascript web application" and it has the following lines of code:
The example below, which includes logic inside views, is something you shouldn’t do:
<div>
<script>
function formatDate(date) {
/* ... */
};
</script>
${ formatDate(this.date) }
</div>
I don't understand what { formatDate(this.date) } means in javascript even in jQuery I have never seen it yet (putting object in jQuery function then I've already seen but the above code is not the case).
Could you explain me what the meaning of it?
Thank you.
${} is a Template Tag, used by jQuery Template Plugin.
${} Template Tag
Used for insertion of data values in the rendered
template. Evaluates the specified field (property) on the current data
item, or the specified JavaScript function or expression.
It's actually a bit more than this: Indeed, the jQuery Template Plugin used to have this syntax ${}. However, currently, this is part of the ES 6 (aka EcmaScript 2015) standard.
Reference: http://exploringjs.com/es6/ch_template-literals.html
I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.