Adding object prototypes dynamically - javascript

Ordinarily in standards JavaScript projects I have a series of Date/Array/String.prototype functions I used regularly and declare using a utilities file.
Trying to use a similar method in Google Apps Script, I'm setting up a library but object prototypes don't carry across when the library is loaded, and aren't recognised when they'd declared in the library and called from a function in the library.
E.g. In library file:
Array.prototype.test = function(){
console.log('test prototype');
}
In file library is used, calling [].test() would error as undefined. The same calling a function in the library with this in it.

Related

How to access to functions/variables from GWT code in Javascript?

I am trying to use some functions from a code that has been obfuscated. So i have an html file that is calling a JS file thru the tag:
<script src="gwt_svg_viewer/gwt_svg_viewer.nocache.js"></script>
that file is defining a function called "onScriptdownloaded" which receives a string like this:
gwt_svg_viewer.onScriptDownloaded(["var $wnd = window.parent;function RE(){}"]);
So my question is how can i access to RE? in another JS file?
It seems that there was a kind of GWT code implemented, but i am not really familiar with that.
Variable names and functions in gwt will be obfuscated every time you compile your project, and variables and functions will be renamed in the process, in order to call a gwt code from javascript in a consistence manner you will need to use jsinterop to export java types. more information can be found in the gwt jsinterop documentation

how to use javascript library in dart

I am learning package:js and the dart file, which is a dart wrapper for chart.js.
I think this file is a bridge which connects dart and javascript. So, in this file, it must tell what javascript library this dart file is trying to connect. Am I right? But I did not find it.
What do the following statements mean? Do the following two statements tell what javascript library this dart file is trying to connect?
#JS('Chart')
library chart.js;
I have no idea how to map functions https://github.com/google/chartjs.dart/blob/master/lib/chartjs.dart to functions in https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js. Anyone can give more tutorials?
You don't need to map to a JavaScript file, you just need to map to JS objects and functions.
You need to add a script tag to index.html that loads the JavaScript file you want to map to, this will make it available globally.
You then need to map
Dart functions to JavaScript functions, so when you call such a Dart function the call will actually be forwarded to the JavaScript function.
Dart classes so that you can use strongly typed Dart classes which will then be converted to and from JavaScript objects when you for example pass them as parameters to mapped functions or get them as return values from such function calls.
#JS('Chart')
library chart.js;
The name chart.js after library is arbitrary. The library directive just needs an unique name.
#JS('Chart') means that the loaded chart.js library is available in JavaScript land under window.Chart (window means global in JS land and is implicit).
#JS()
class Chart {
declares a Dart class Chart and #JS() maps it to a JS class with the same name in the library scope declared above. So the Dart class Chart will map to the JavaScript class window.Chart.Chart.
external factory Chart(
The external ... declarations inside the Dart Chart class map to the JS methods with the same name.
More details can be found in the README.md https://pub.dartlang.org/packages/js.
If you're still stuck you can ask more concrete questions. It's difficult to answer generic questions about how to use a package.

Calling Functions in Different JavaScript Files With Node.js

I have a Node.js library file that is required by my Node.js application file, exporting a function.
In the application file I am calling the exported function, passing it some parameters, and it is working fine.
In one of the parameters, I would like to send the name of a function that is declared in the application file; this is so that the parameters can be JSONified. However, the code in the library file cannot find the function by name, because it exists in another file (the application one).
I know I can get over this by passing a pointer to the function, instead of its name, but because of serialization (functions cannot be serialized), I would like to pass the name.
I cannot just export the function from the application file and import it in the library file because that would be a circular reference, and, of course, the library file does not need to know about the application one.
What is the recommended pattern for dealing with this kind of situations?
The recommended pattern is still to probably pass a function object - why does your function get serialized when you pass a reference to it?
A really easy alternative would be to just define your function in the global scope but this pollutes the global scope and goes against the really awesome encapsulated way we write nodejs code:
global.yourCallback = function() { ... }
and now the string yourCallback will work.
You could register the function with your library in advance, in a kind of configuration-stage or when loading/defining the function:
var mylib = require('./mylib')
function myfunc(){
// ...
}
mylib.register('myfunc', myfunc);
Assuming the registration is done at start-up then the library and consumers of the library would be able to refer to it as 'myfunc'.
Other libraries/frameworks such as AngularJS do similar things, e.g.:
angularModule.controller('MyController', function(){/*...*/});

Unique instances of Javascript self-executing anonymous functions

I have created the PHP side of a modular AJAX/PHP framework and now I am trying to implement the client side.
From my previous experience with modular web applications I know that sometimes multiple instances of one particular module are needed. For example, a web based two player game with page parts for each user.
On PHP side I have assigned a unque ID to each constructed instance of the module and I can pass this UID to the browser but I have no idea how to implement the Javascript side of this module instance.
Modules can be loaded all in one go or loaded separately through AJAX (I am using jQuery).
Now I am using a modular approach that I found in some article, but I can redesign it in some other way if that would help to solve this issue without sacrifising modularity and private/public code separation. For now let's say I have a js file with the following:
//Self-Executing Anonymous Func
(function( MyModule, $, undefined ) {
// My Uid
MyModule.UID = "";
//Public Method
MyModule.onLoad = function() {
alert("Hey, you loaded an instance of MyModule with UID " + MyModule.UID);
};
//Private Methods follow
function somethingPrivate( ) {
}
}( window.MyModule = window.MyModule|| {}, jQuery ));
I am using Smarty for templates. Let's say, I have a simple module template like this:
<div id="{$contents.moduleuid}">
here goes the contents of the module which can be accessed from MyModule Javascript code by using this unique moduleuid
</div>
I have set up the server side so each module automatically appends additional template with Javascript:
<script type="text/javascript">
/*
TODO: here I have access to the {$contents.moduleuid}
But I have no idea what to put here to create a unique instance of MyModule
(also it might need loading js file if it was not loaded yet) and I should also set for
this instance MyModule.UID to {$contents.moduleuid}
and also call MyModule.onLoad for this instance after it has loaded its Javascript.
*/
</script>
I am not experienced with advanced Javascript topics so it is unclear to me how I can create a separate instance of MyModule for each module which gets construced server-side? Is it possible at all to create instances of self-executing anonymous functions? If not, then how can I implement and clone Javascript objects with separated private/public code?
My recommendation is to keep the client side and server side loosely coupled. Try to build your modular client application completely with HTML/JS without PHP tricks on it. As I understand, each of your module (or UI component) need to be loosely coupled from the others. In such case there are several other concerns you might need to look for:
How to keep your UI component structure (html), presentation (css) and behavior (JS) self contained (for example in a single folder), so that it can live or die independently
How these self contained components interact with each other
How to manage the configurations/settings of your UI components
Should you be using MVVM or MVC pattern to organize and bind the view to your PHP model
Who decides when to create/show/hide your UI components (for example based on URL for bookmarking)
If your client is a large and complex application, you might need to look for other concerns such as JS optimization, unit testing, documentation, product sub modules, etc.
Have a look at the BoilerplateJS Javascript reference architecture we put forward at http://boilerplatejs.org. It suggests ways to address all concerns I discussed above.
Since you are already using jQuery, you could create a jQuery plugin. The plugin should behave the way you need, and I believe you won't even need a unique ID. Considering each of your module's instance is contained in a div with class module-container, your jQuery code for adding client-side behavior to the divs would be something like this:
$(function(){
// DOM content is loaded
$('.module-container').MyPluginName();
});
The minimal plugin code would be (considering it's in a separate .js file):
(function($){
$.fn.MyPluginName = function() {
// Return this.each to maintain chainability
return this.each(function() {
// Keep a reference to your unique div instance.
var $this = $(this);
// Plugin logic here
});
};
})(jQuery);
If you are using jQueryUI, I also recommend you also look into the "widget factory" (intro, docs), which serves as a base for building powerful, normalized jQuery plugins.

"Can't find variable" error with Rails 3.1 and Coffeescript

I have views in my application that reference my application.js file which contains functions I use throughout my application.
I just installed the Rails 3.1 release candidate after having used the edge version of 3.1. Until I installed the RC I wasn't having any problems but now I'm getting this error:
ReferenceError: Can't find variable: indicator_tag
indicator_tag is a function I defined in application.js.
The only difference I notice in the javascript file is that now all my functions are wrapped in:
(function() { ... }).call(this);
I understand this is for variable scoping? But could it be preventing my pages from using those variables? And before anyone asks, I've made sure the javascript paths are correct in my include tags.
By default, every CoffeeScript file is compiled down into a closure. You cannot interact with functions from a different file, unless you export them to a global variable. I'd recommend doing something like this:
On top of every coffeescript file, add a line like
window.Application ||= {}
This will ensure that there's a global named Application present at all times.
Now, for every function that you'll have the need to call from another file, define them as
Application.indicator_tag = (el) ->
...
and call them using
Application.indicator_tag(params)
Dogbert's solution is a great way to go if you have a very sophisticated JS back-end. However, there's a much simpler solution if you only have a handful of functions you're working with. Just add them directly to the window object, like this:
window.indicator_tag = (el) ->
...
Then you can use your functions from anywhere without having to wrap them up in another object.

Categories

Resources