JavaScript - Front-end MVC - javascript

My actual question here:
I'm wondering if (beargrylls.com) uses Django or it's packages. Or some other framework. Or a custom framework? Also, if you take a look at the website (beargrylls.com), you can see that it uses a lot of paralax scrolling, sliders and cool animations. Is this custom-made or is this another framework/plugin/whatever?
If found an awesome website (beargrylls.com) on awwwards.com. I'm familiar with the MVC model that Laravel uses. So I know the basics. But I found out that (beargrylls.com) uses some kind of routing inside it's scripts!?
What I also found remarkanble is that the script(s) and the entite css of the website is loaded in inline HTML. So there are no HTTP requests, no files to load except the images
Which framework/plugin compiles this?
Example:
, Route = function t() {
classCallCheck(this, t);
var e = new Router({
xhr: !0
});
e.get("/", HomeController),
e.get("/about", AboutController),
e.get("/television", TelevisionController),
e.get("/live", LiveController),
e.get("/experiences", ExperiencesController),
e.get("/socialwall", SocialwallController),
e.get("/adventurers", AdventurersController),
e.get("/termsofuse", TermsofuseController),
e.get("/faqs", FaqsController),
e.get("/signup", SignupController),
e.error(ErrorController),
e.run()
}
, App = function t() {
classCallCheck(this, t),
Support.init(),
index.TopWhenRefresh(),
new Route
};
new App;
Another example that boosted my suspisions can be found inside it's createClass function or class. Where it assumably creates classes.
this.backgroundWrap = index.Geb.id("h-header-background-wrap"),
this.centerWrap = index.Geb.id("h-header-center-wrap"),
this.foregroundWrap = index.Geb.id("h-header-foreground-wrap"),
this.titleWrap = index.Geb.id("h-header-title-wrap"),
this.introTxt = index.Geb.id("h-intro-txt"),
this.introLine = index.Geb.id("h-intro-line"),
this.introVideo = index.Geb.id("h-intro-video"),
this.introScroll = index.Geb.id("h-intro-scroll"),
this.nav = index.Geb.class("nav")[0],
this.progress = index.Geb.id("h-intro-progress"),
this.scrollLineWrap = index.Geb.id("h-header-scroll-line-wrap"),
this.scrollTxtWrap = index.Geb.id("h-header-scroll-txt-wrap"),
this.stickyBurger = index.Geb.id("sticky-burger"),
So it seems to me that almost this entire website (routing, element classes and more) is created trough this script. I even see some mailchimp tags here.
I looked into the Django framework because of some of the links to media folders like /static/.

Penryn-starter
A starter kit for web development.
Docker
Browsersync
PHP 7.1.8
PostCSS
Css Nano
ES2015
ESLint
Rollup
Uglify JS 3
Skylake
https://github.com/ariiiman/penryn-starter
Skylake:
It's a Light JavaScript library named Skylake:
https://github.com/ariiiman/skylake
example:
const animation = new S.Merom('.element', '3dy', 0, 100, 1000, 'Power4InOut')
animation.play()
animation.reverse()
Similar functions can also be found in the Sources tab of the Google Devtools on beargrylls.com:
this.tlImg.from(this.background, "3dy", 10, 0, 2e3, "ExpoOut")
Also, in the script can skylake be found litterally:
scroll: {
throttle: !0,
skylake: "Scroll"
},
But I'm not quite sure what this actually does. I can't explain the routing class or anything of that sort. But it defenitely uses this Skylake library.
The same structure of code can be found on these websites: https://www.aristidebenoist.com/ (author of Skylake) and on http://www.jennyjohannesson.com/
though I do not think that these websites are using Skylake. Or just use other variables or something. But this:
, App = function e() {
classCallCheck(this, e),
Support.init(),
index.TopWhenRefresh(),
new Router({
xhr: !0
})
};
!function(e) {
new App
}();
}
)();
is exactly the same as on beargrylls.com
also the almost exact same Route class can be found on http://www.jennyjohannesson.com/

Related

How can I access the DOM of a <webview> in Electron?

I'm just getting started with Electron, with prior experience with node-webkit (nw.js).
In nw.js, I was able to create iframes and then access the DOM of said iframe in order to grab things like the title, favicon, &c. When I picked up Electron a few days ago to port my nw.js app to it, I saw advice to use webviews instead of iframes, simply because they were better. Now, the functionality I mentioned above was relatively easy to do in nw.js, but I don't know how to do it in Electron (and examples are slim to none). Can anyone help?
Also, I have back/forward buttons for my webview (and I intend on having more than one). I saw in the documentation that I could call functions for doing so on a webview, but nothing I have tried worked either (and, I haven't found examples of them being used in the wild).
I dunno who voted to close my question, but I'm glad it didn't go through. Other people have this question elsewhere online too. I also explained what I wanted to achieve, but w/e.
I ended up using ipc-message. The documentation could use more examples/explanations for the layperson, but hey, I figured it out. My code is here and here, but I will also post examples below should my code disappear for whatever reason.
This code is in aries.js, and this file is included in the main renderer page, which is index.html.
var ipc = require("ipc");
var webview = document.getElementsByClassName("tabs-pane active")[0];
webview.addEventListener("ipc-message", function (e) {
if (e.channel === "window-data") {
// console.log(e.args[0]);
$(".tab.active .tab-favicon").attr("src", e.args[0].favicon);
$(".tab.active .tab-title").html(e.args[0].title);
$("#url-bar").val(e.args[0].url);
$("#aries-titlebar h1").html("Aries | " + e.args[0].title);
}
// TODO
// Make this better...cancel out setTimeout?
var timer;
if (e.channel === "mouseover-href") {
// console.log(e.args[0]);
$(".linker").html(e.args[0]).stop().addClass("active");
clearTimeout(timer);
timer = setTimeout(function () {
$(".linker").stop().removeClass("active");
}, 1500);
}
});
This next bit of code is in browser.js, and this file gets injected into my <webview>.
var ipc = require("ipc");
document.addEventListener("mouseover", function (e) {
var hoveredEl = e.target;
if (hoveredEl.tagName !== "A") {
return;
}
ipc.sendToHost("mouseover-href", hoveredEl.href);
});
document.addEventListener("DOMContentLoaded", function () {
var data = {
"title": document.title,
"url": window.location.href,
// need to make my own version, can't rely on Google forever
// maybe have this URL fetcher hosted on hikar.io?
"favicon": "https://www.google.com/s2/favicons?domain=" + window.location.href
};
ipc.sendToHost("window-data", data);
});
I haven't found a reliable way to inject jQuery into <webview>s, and I probably shouldn't because the page I would be injecting might already have it (in case you're wondering why my main code is jQuery, but there's also regular JavaScript).
Besides guest to host IPC calls as NetOperatorWibby, it is also very useful to go from host to guest. The only way to do this at present is to use the <webview>.executeJavaScript(code, userGesture). This api is a bit crude but it works.
If you are working with a remote guest, like "extending" a third party web page, you can also utilize webview preload attribute which executes your custom script before any other scripts are run on the page. Just note that the preload api, for security reasons, will nuke any functions that are created in the root namespace of your custom JS file when your custom script finishes, however this custodial process will not nuke any objects you declare in the root. So if you want your custom functions to persist, bundle them into a singleton object and your custom APIs will persist after the page fully loads.
[update] Here is a simple example that I just finished writing: Electron-Webview-Host-to-Guest-RPC-Sample
This relates to previous answer (I am not allowed to comment): Important info regarding ipc module for users of Electron 1.x:
The ipc module was split into two separate modules:
ipcMain for the main process
ipcRenderer for the renderer process
So, the above examples need to be corrected, instead of
// Outdated - doesn't work in 1.x
var ipc = require("ipc");
use:
// In main process.
var ipcMain = require('electron').ipcMain
And:
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer
See: http://electron.atom.io/blog/2015/11/17/electron-api-changes section on 'Splitting the ipc module'

non-concatenated dat.gui source with require.js. Customising, or templating dat.gui

Please excuse the SEO friendly title, but I would like to make the problem I am currently solving as accessible as possible. For those of you who are looking to customise the look and feel of dat.gui, you need to download the source and include it using require.js using the instructions here: https://code.google.com/p/dat-gui/.
And now my question.
I am working on a project that requires building a UI with heavy live integration with Javascript (I'm using three.js) and I have decided to modify dat.gui to create this ui; with a view to soon integrate it with backbone.js as a collection of views.
I wish to switch to use the dat.gui source files to edit the styling
To start, I switched over from the concatenated dat.gui.min.js, to the source using the instructions in the link above. I put the whole source in its own folder within my libraries folder, and placed the main.js file the require.js err... requires within the "src" folder. I did this due to linking dependencies within dat.gui's "GUI.js".
Everything seems to link up properly, and I am using essentially the same code as I did before to create my dat.guis, but I keep getting undefined errors, depending on how I change the gui variable either in my original code or in main.js. My understanding of require.js is VERY limited and I feel it is something integral to how it works (and that it's defiantly one of those oh so simple problems for someone with the know how)
Here's my main.js file located at /libraries/dat-gui/src
(this dir also includes text.js)
//This is main.js for using require.js
require([
'dat/gui/GUI'
], function(GUI) {
// No namespace necessary
var gui = new GUI();
});
and here's the bones of my original dat.gui definition code:
////////////////////////////////////////////////DatGui/////////////////////////////////////////////////////
var stageConfigData = function() {
this.scaleX = params.stageWidth;
this.scaleZ = params.stageDepth;
this.spinTheCamera = false;
this.lightIntensity = 1;
this.lightDistance = 0;
this.lightFrontColour = "#ffb752";
this.lightRearColour = "#3535fa";
this.lockCameraToScene = true;
this.tooltype = 3;
this.objectSelect = 'Man';
this.saveJSON = function(){
saveJSON();
};
};
var stageConfig = new stageConfigData( );
var moveConfig = new moveConfigData( );
///I think the problem is linked to defining this variable:
//var gui = new dat.GUI();//works for the minified version
var gui = new dat.GUI();//for non-concatenated
var fstage = gui.addFolder('Stage');
var fcamera = gui.addFolder('Camera');
var ffhouselts = gui.addFolder('Front of House Lights');
var fRearlts = gui.addFolder('Rear Lights');
var sandl = gui.addFolder('Saving and Loading');
fstage.add( stageConfig, 'scaleX', 1, 100, 5).name('Width of stage').onChange( function(){
stage.scale.x = ( stageConfig.scaleX );
});
fstage.add( stageConfig, 'scaleZ', 1, 100, 5).name('Depth of stage').onChange( function(){
stage.scale.z = ( stageConfig.scaleZ );
});
... //there's more but i think it's irrelevant
and the errors i am getting are either:
Uncaught ReferenceError: dat is not defined
or
Uncaught ReferenceError: GUI is not defined
depending on how I mess with those variables and the bit in main.js under //No namespace necessary. I don't understand how namespaces work as I am quite new to javascript as a whole.
Has anyone any ideas? Again, I'd say this is probably one of those real dunce moments, but I would really appreciate the help nonetheless.
Thanks a lot!
When you use require.js method there will be no global object. But you can create it yourself
require([
'dat/gui/GUI'
], function(GUI) {
window.dat = {
GUI: GUI
};
});

Preloading of Javascript Files

Working on a small engine to run my HTML5 test games, using it as a great way to get deeper into Javascript and have fun at the same time. Succeeding, btw.
However, I just found this cool little script called PreloadJS ( http://www.createjs.com/#!/PreloadJS ). Also using John Resig's classical inheritence class JS. Very cool, enjoying it. I am attempting to use PreloadJS to pull in all of my engine files...but I seem to be having an issue. Here's the code I'm using (keeping it simple on purpose):
var ScriptLoader = Class.extend({ // Want to add functionality to this to allow PHP or inline loading...perhaps later
init: function() {
this.fileList = [
'Empty.js',
'./engine/Scene.js'
];
this.preload;
},
loadProjectSource: function(directory) {
if (this.preload != null) { this.preload.close(); }
this.preload = new createjs.LoadQueue();
this.preload.addEventListener("fileload", this.fileLoaded);
this.preload.addEventListener("error", this.fileError);
this.preload.setMaxConnections(5);
this.loadAnother();
},
loadAnother: function() {
var item = this.fileList.shift();
if(this.fileList.length != 0) {
this.preload.loadFile(item);
}
},
fileLoaded: function(e) {
debug('Loaded ' + e.item.src);
this.loadAnother();
},
fileError: function(e) {
debug('Error ' + e.item.src);
}
}
From my engine instantiation, I'm calling ScriptLoader.loadProjectSource. It's doing nothing but throwing errors, and the documentation on error handling (and loading JS files in general...) is very sparse on the PreloadJS site. It focuses on preloading images (which, admittedly, looks great). Anyway, so yea, it's throwing errors. And it can't be the files, as I tried loading a completely blank JS file (as you can see). Still throwing an error on the Empty.js file.
Annoyed :) Thanks in advance.
The PreloadJS script uses XHR where available with browser support. In order for this to function correctly with locally-hosted scripts, a local webserver must be running. Upon activating my local webserver and attempting the same operation, full success.

Auto-load/include for JavaScript

I have file called common.js and it's included in each page of my site using <script />.
It will grow fast as my sites functionality will grow (I hope; I imagine). :)
Lets example I have a jQuery event:
$('#that').click(function() {
one_of_many_functions($(this));
}
For the moment, I have that one_of_many_functions() in common.js.
Is it somehow possible that JavaScript automatically loads file one_of_many_functions.js when such function is called, but it doesn't exist? Like auto-loader. :)
The second option I see is to do something like:
$('#that').click(function() {
include('one_of_many_functions');
one_of_many_functions($(this));
}
That not so automatically, but still - includes wanted file.
Is any of this possible? Thanks in an advice! :)
It is not possible to directly auto-load external javascripts on demand. It is, however, possible to implement a dynamic inclusion mechanism similar to the second route you mentioned.
There are some challenges though. When you "include" a new external script, you aren't going to be able to immediately use the included functionality, you'll have to wait until the script loads. This means that you'll have to fragment your code somewhat, which means that you'll have to make some decisions about what should just be included in the core vs. what can be included on demand.
You'll need to set up a central object that keeps track of which assets are already loaded. Here's a quick mockup of that:
var assets = {
assets: {},
include: function (asset_name, callback) {
if (typeof callback != 'function')
callback = function () { return false; };
if (typeof this.assets[asset_name] != 'undefined' )
return callback();
var html_doc = document.getElementsByTagName('head')[0];
var st = document.createElement('script');
st.setAttribute('language', 'javascript');
st.setAttribute('type', 'text/javascript');
st.setAttribute('src', asset_name);
st.onload = function () { assets._script_loaded(asset_name, callback); };
html_doc.appendChild(st);
},
_script_loaded: function (asset_name, callback) {
this.assets[asset_name] = true;
callback();
}
};
assets.inlude('myfile.js', function () {
/* do stuff that depends on myfile.js */
});
Sure it's possible -- but this can become painful to manage. In order to implement something like this, you're going to have to maintain an index of functions and their corresponding source file. As your project grows, this can be troublesome for a few reasons -- the 2 that stick out in my mind are:
A) You have the added responsibility of maintaining your index object/lookup mechanism so that your scripts know where to look when the function you're calling cannot be found.
B) This is one more thing that can go wrong when debugging your growing project.
I'm sure that someone else will mention this by the time I'm finished writing this, but your time would probably be better spent figuring out how to combine all of your code into a single .js file. The benefits to doing so are well-documented.
I have created something close to that a year ago. In fact, I have found this thread by search if that is something new on the field. You can see what I have created here: https://github.com/thiagomata/CanvasBox/blob/master/src/main/New.js
My project are, almost 100% OOP. So, I used this fact to focus my solution. I create this "Class" with the name "New" what is used to, first load and after instance the objects.
Here a example of someone using it:
var objSquare = New.Square(); // Square is loaded and after that instance is created
objSquare.x = objBox.width / 2;
objSquare.y = objBox.height / 2;
var objSomeExample = New.Stuff("some parameters can be sent too");
In this version I am not using some json with all js file position. The mapping is hardcore as you can see here:
New.prototype.arrMap = {
CanvasBox: "" + window.MAIN_PATH + "CanvasBox",
CanvasBoxBehavior: "" + window.MAIN_PATH + "CanvasBoxBehavior",
CanvasBoxButton: "" + window.MAIN_PATH + "CanvasBoxButton",
// (...)
};
But make this more automatic, using gulp or grunt is something what I am thinking to do, and it is not that hard.
This solution was created to be used into the project. So, the code may need some changes to be able to be used into any project. But may be a start.
Hope this helps.
As I said before, this still is a working progress. But I have created a more independent module what use gulp to keep it updated.
All the magic que be found in this links:
https://github.com/thiagomata/CanvasBox/blob/master/src/coffee/main/Instance.coffee
https://github.com/thiagomata/CanvasBox/blob/master/src/node/scripts.js
https://github.com/thiagomata/CanvasBox/blob/master/gulpfile.js
A special look should be in this lines of the Instance.coffee
###
# Create an instance of the object passing the argument
###
instaceObject = (->
ClassElement = (args) ->
window[args["0"]].apply this, args["1"]
->
ClassElement:: = (window[arguments["0"]])::
objElement = new ClassElement(arguments)
return objElement
)()
This lines allows me to initialize a instance of some object after load its file. As is used in the create method:
create:()->
#load()
return instaceObject(#packageName, arguments)

How can I easily maintain a cross-file JavaScript Library Development Environment

I have been developing a new JavaScript application which is rapidly growing in size.
My entire JavaScript Application has been encapsulated inside a single function, in a single file, in a way like this:
(function(){
var uniqueApplication = window.uniqueApplication = function(opts){
if (opts.featureOne)
{
this.featureOne = new featureOne(opts.featureOne);
}
if (opts.featureTwo)
{
this.featureTwo = new featureTwo(opts.featureTwo);
}
if (opts.featureThree)
{
this.featureThree = new featureThree(opts.featureThree);
}
};
var featureOne = function(options)
{
this.options = options;
};
featureOne.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
var featureTwo = function(options)
{
this.options = options;
};
featureTwo.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
var featureThree = function(options)
{
this.options = options;
};
featureThree.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
})();
In the same file after the anonymous function and execution I do something like this:
(function(){
var instanceOfApplication = new uniqueApplication({
featureOne:"dataSource",
featureTwo:"drawingCanvas",
featureThree:3540
});
})();
Before uploading this software online I pass my JavaScript file, and all it's dependencies, into Google Closure Compiler, using just the default Compression, and then I have one nice JavaScript file ready to go online for production.
This technique has worked marvelously for me - as it has created only one global footprint in the DOM and has given me a very flexible framework to grow each additional feature of the application. However - I am reaching the point where I'd really rather not keep this entire application inside one JavaScript file.
I'd like to move from having one large uniqueApplication.js file during development to having a separate file for each feature in the application, featureOne.js - featureTwo.js - featureThree.js
Once I have completed offline development testing, I would then like to use something, perhaps Google Closure Compiler, to combine all of these files together - however I want these files to all be compiled inside of that scope, as they are when I have them inside one file - and I would like for them to remain in the same scope during offline testing too.
I see that Google Closure Compiler supports an argument for passing in modules but I haven't really been able to find a whole lot of information on doing something like this.
Anybody have any idea how this could be accomplished - or any suggestions on a development practice for writing a single JavaScript Library across multiple files that still only leaves one footprint on the DOM?
The jQuery github has a similar setup to the one you speak of. There is even a Makefile / ant build.xml that use the google closure complier.
The basic concept is to develop all your stuff in separate files, then use cat (or something similar) to put all the files together.
cat intro.js core.js featureOne.js featureTwo.js featureThree.js outro.js > build/script.js
The code inside intro.js and outro.js from jQuery:
// intro.js
(function(window, undefined) {
// outro.js
})(window);
Take a look at how this library is built
http://github.com/oyvindkinsey/easyXDM
The files are separated, but merged together, placed into a closure, and run through jslint by the ant script (build.xml).
The ant script also does conditional 'compilation', string replacements and minification.
I recommend that you split your code base into AMD/RequireJS-style modules.
The AMD format seems to meet most of your requirements, and is rapidly becoming a de facto standard.

Categories

Resources