Extend c3js library to include my own functionality & features - javascript

How can I extend http://c3js.org/ library, I wanted to replace its internal initialisation function or redrawing functions with my own code.
c3_chart_internal_fn.initParams = function () {}

You can see in http://github.com/masayuki0812/c3/releases/tag/0.3.0 the new architecture that supports extensions.

It looks like that is defined here:
https://github.com/masayuki0812/c3/blob/master/src/core.js
So yes, you could download the source from github and make your desired changes.
This library uses Grunt to concatenate (and minify) all the source files into the single library file used by your web pages. The gruntfile is in the sources as well. If you are not familiar with grunt, see: http://gruntjs.com/
Alternatively, it looks like c3_chart_internal_fn is global. If that is true, you may be able to simply redefine c3_chart_internal_fn.initParams after you load the library (sigma.js plugins work that way).
However, I have not looked at the code carefully enough to see when this function gets called. If it is called as soon as the library loads (as part of an immediately evaluated function), then it will be too late to redefine. However, if it is called when you init the library in your page's script, then that would work.
HTH.

Related

How to include OVRManager in Three.js Scene?

I have created several Three.js/Javascript demo applications that I'm experimenting with in my new Oculus Go. I'm trying to enable the Go Controller to do stuff in my applications, and according to the Oculus Developer Center, the best thing to do is to include OVRManager in my scene so I have access to that API. That sounds good, but for all the documentation (https://developer.oculus.com/documentation/unity/latest/concepts/unity-ovrinput/) I can't see HOW to add OVRManager to my scene! I have not worked with Unity before, but from what I can tell in the documentation there shouldn't be any compatibility issues (should there?)
So what I'd think to do is something like:
<script src="OVRManager.js or something like that"></script>
and then call the functions I need, as I've done with OrbitControls.js and other external dependencies.
But for the life of me, Google searching is just sending me in circles. I see questions posed for C++ and C# but that's of no use to me. How do I get this API working in my Three.js scene? Where do I find it and is there some other way to include it?
Thanks!
Create a unity WebGL build and expose the API you need as public methods in a Unity Script you attach to a GameObject.
Then, you should be able to follow the directions at How to call Unity functions from javascript (copied below) on how to call those methods from your javascript code.
You may be able to use UnityScript, which is vaguely similar to JavaScript, to write the Script if you use an old version of Unity. As of this writing, Oculus recommends version 2017.4.11f1, which I think might still support UnityScript.
One major reason you see so much less UnityScript information is that Unity has been moving away from UnityScript, into only supporting C#.
But regardless of if you code your OVRManager script in C# or UnityScript, Unity will make the methods callable from your JavaScript.
Calling Unity scripts functions from JavaScript
Sometimes you need to send some data or notification to the Unity
script from the browser’s JavaScript. The recommended way of doing it
is to call methods on GameObjects in your content. If you are making
the call from a JavaScript plugin, embedded in your project, you can
use the following code:
SendMessage(objectName, methodName, value);
Where objectName is the name of an object in your scene; methodName is
the name of a method in the script, currently attached to that object;
value can be a string, a number, or can be empty. For example:
SendMessage('MyGameObject', 'MyFunction');
SendMessage('MyGameObject', 'MyFunction', 5);
SendMessage('MyGameObject', 'MyFunction', 'MyString');
If you would like to make a call from the global scope of the
embedding page, see the Code Visibility section below.
Code visibility
Starting from Unity 5.6 all the build code is executed in its own
scope. This approach makes it possible to embed your game on an
arbitrary page without causing conflicts with the embedding page code,
as well as makes it possible to embed more than one build on the same
page.
If you have all your JavaScript code in the form of .jslib plugins
inside your project, then this JavaScript code will run inside the
same scope as the compiled build and your code should work pretty much
the same way as in previous versions of Unity (for example, the
following objects and functions should be directly visible from the
JavaScript plugin code: Module, SendMessage, HEAP8, ccall etc.).
However, if you are planning to call the internal JavaScript functions
from the global scope of the embedding page, you should always assume
that there are multiple builds embedded on the page, so you should
explicitly specify which build you are referencing to. For example, if
your game has been instantiated as:
var gameInstance = UnityLoader.instantiate("gameContainer", "Build/build.json", {onProgress: UnityProgress});
Then you can send a message to the build using
gameInstance.SendMessage(), or access the build Module object using
gameInstance.Module.

How to create and implement a custom JavaScript library

I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.
If I have a standalone file Utilities.js
var Utilities=
{
show: function(input)
{
alert(input);
}
};
Am I missing something as to how a library should be defined standalone?
My second question is how to use that is sub-sequent js files. What I did so far is:
<script type="text/javascript" src="resources/Utilities.js"></script>
In my index.html. Is this enough to reference it as:
Utilities.show("Hello");
In any other java script file?
I tested it in this fashion and got and error "Utilities is not defined"
NOTE: This is just an example and not my full and practical purpose.
Yes, including that Javascript file with that global variable declared is enough to call your methods this way Utilities.show("Hello"); from another Javascript file loaded after Utilities.js or inside a <script></script> section of your html.
But you can actually improve it a little, following the module pattern and exposing only the functions you really need to the global scope (you'll likely write some functions that the users of your library should not call directly, this allows you to do it in a clean way):
var Utilities=Utilities||(function () {
//Accessible only here
var privateArray=[];
//Cannot be called from outside this function
var privateFunction=function(){
}
//Return only what must be publicly accessible, in this
//case only the show() method
return {
show: function(input){
privateFunction();
alert(input);
}
}
})();
That (function () { /* Code */})();, defining a new scope for your code will also avoid name clashes with other global javascript object/functions.
It is OK to use object literals, but you can define libraries using other patterns (module, revealing module, constructors, etc).
I recommend these links to understand primitives, scopes, closures, object literals, etc.
http://bonsaiden.github.io/JavaScript-Garden/
http://jsbooks.revolunet.com/
To call the method inside index.html you need to add a tag.
<script>
Utilities.show("Hello");
</script>
But this approach it's not recommended. Instead of it, you can create a new JS file to run your library code.
<script type="text/javascript" src="resources/Utilities.js"></script>
<script type="text/javascript" src="resources/main.js"></script>
In main.js
Utilities.show("Hello");
Hope it helps.
Given the fact that you gave, within yout question, zero context of what you're trying to achieve, the best answer to your original question is that it depends.
If you just need a bunch of files and you're done (like in your example, Utilities.js and a few more) then you're ok with the way you're heading to.
But of course, you'll allways want to scale your front end and thus you should adhere to some architectural pattern. So, if you're building a client side (browser-side) application, then you should really implement your libraries using the module pattern, and begin your project from a good project example / scaffold.
On the other hand, if you're rendering the html on server (e.g. you're using PHP to render the final html file that will be sent to browser) and you just need some thin functionality in the browser, the way you begun can be okay if you're careful. Also, you can still implement the module pattern here too, although I strongly suggest that you should make use of namespacing to have a clear separation of concerns.
In browser based javascript you can't just call functions from different files yet. In Es6 there are ways. But not yet. Which mean just because you have some variable or function etc then you cant reference it automatically in another file.
Unless both files are loaded into one html and are loaded in order.
Alternatively you could run task runner like grunt and 'merge' them upon each build.
Javascript doesnt have special concept of library, in es6 it's a little different, everything is an object.
What you are doing is just creating an object. and yes it will work.

Make an external Script available to all members of qooxdoo Object

So I have been making a web app in the qooxdoo framework that utilised the d3 library. At the moment, every function which needs to use the d3 library works like this:
myFunction : function() {
var req = new qx.bom.request.Script();
req.onload = this.myActualFunction(); //calls function when script loads
req.open("GET","http://d3js.org/d3.v3.js" );
req.send();
}
It seems verbose to have to call the script loader for lots of different functions*. We could, and eventually probably will, switch to using d3 from a local directory. Nevertheless, it seems like there are lots of times when you would like to use a script loader to make a script available to, say, every member function of an object. Is there someway that I can achieve that? If I passed the script loader around like a variable, does that mean that every function which has it in scope gets access to the library?
The Manual did not appear very helpful on this topic.
*I presume that qooxdoo arranges to cache the script - it seems to be pretty good at those type of optimisations, though I have no specific knowledge of how the script loaders are treated in the compiled version.
The best approach of handling an external library is to create a Qooxdoo wrapper which will be a first-class citizen in the dependency management process. Qooxdoo internally makes use of this approach, e.g. Sizzle, Mustache, etc. Luckily for you there's already a contribution for D3. Though you can make your own wrapper without a hassle.
You can also, use add-script to "link" the library to the document but I see this way mostly disadvantageous.

Does anyone know of a way to dynamically load a qooxdoo module?

I'm using the latest qooxdoo SDK (3.5) and am trying to find a way to dynamically load a module. Each module would implement an "init" function which creates a window in the application and, from that point, is self-contained.
What I would need is the ability to call an arbitrary init function without knowing the module existed beforehand. For example, someone uploads a custom module and tries to run it--I just need to call the module's init function (or error out if the call fails).
Any ideas?
Edit:
Something like:
function loadModule(modName) {
var mod = new qx.something.loadModule(modName);
mod.init();
}
I found 3 ways that Qooxdoo has to run dynamic code. The first way is via the built-in parts loader. "Parts" are basically portions of an application that qooxdoo will load "just-in-time" when you actually need them--for example, a class that operates a rarely used form or dialog box. This method is not truly dynamic (in my opinion) in that it requires the code to be included in the build process that Qooxdoo provides. Explaining exactly how it works is out of scope for this answer and, frankly, I'm not yet all that familiar with it myself.
The second way is via the qx.Class.getByName() function call. It works like so:
qx.Class.define("Bacon", {
extend: qx.core.Object,
construct: function(foo, bar) {
this.foo = foo;
this.bar = bar;
}
});
var klass = qx.Class.getByName("Bacon");
var obj = new klass("foo", "bar");
this.debug(obj.foo);
This method was found on the Qooxdoo mailing list here. This method will work for code included in the build process and for code introduced dynamically but, in my opinion, is trumped by the third method for the simple reason that if you are introducing a new class dynamically, you'll have to use the third method anyway.
The final method I located was actually revealed to me via studying the source code for the Qooxdoo playground. (The source code is available as part of the desktop download.)
The playground reads the code in from the editor and creates an anonymous function out of it, then executes the function. There is a bunch of setup and tear-down the playground does surrounding the following code, but I've removed it for brevity and clarity. If you are interested in doing something similar yourself, I highly recommend viewing the source code for the playground application. The dynamic code execution is contained within the __updatePlayground function starting on line 810 (Qooxdoo v3.5).
var fun;
try {
fun = qx.event.GlobalError.observeMethod(new Function(code));
} catch(ex) {
//do something with the exception
}
try {
fun.call();
} catch(ex) {
//do something with the exception
}
The code is straightforward and uses the built-in Javascript function "call" to execute the anonymous function.
Please define module.
Qooxdoo source code uses the same convention as Java - one class per file. Do you really want to load classes individually and deal with dependencies? If not, what's your definition of a module?
Other than that, qooxdoo has a notion of packages, which are groups of classes, interfaces and mixins, framework, contribs, including the framework itself, packed by the generator in an optimized way, so that the classes used earlier are loaded earlier. Using qooxdoo's own packaging mechanism requires no more effort than running build with custom arguments or customizing the config.json - all described in detail in the manual.
If your idea of a module is sort of a sub-application, mostly decoupled from everything else in the big application, I'm not sure it's achievable without either significantly modifying the generator code (what ./generate.py calls) or accepting some size overhead.
I won't go into details of modifying the generator - if you go this route you'll need to dig deeply anyway, and you'll learn more than I know about the generator.
What you can do while staying within what qooxdoo allows is to create a separate island application for each module, build your own infrastructure for inter-modules communication via JavaScript attached to the top window, and run the modules inside the main page, with some manually added magic to make the various modules behave like tab panes or qooxdoo windows. The overhead you'll have to take, besides some awkward custom, non-qooxdoo code, is that all modules will re-load the qooxdoo framework code.

Organizing javascript in Rails app

I have several javascript (coffee script) files in my Rails javascripts directory. The code is logically divided into different files. However, each file starts with $(document).ready -> and some files share common helper functions.
What is the best way to factor out the helper functions? Should I just put them all in some other file that gets included earlier in application.js?
Also, is it normal to have the code divided up the way mine is, where every page does $(document).ready ->? Doesn't this mean that all of my code is called on every page, regardless of whether or not it is relevant? Are there alternatives to this organization?
I'm not sure if this question is specific to Rails or relevant to javascript and jQuery in general.
I do think this is a Rails question, and a good one.
The normal paradigm in Rails, where "global" stuff goes in application.* is a little messed up with the asset pipeline, since the application.js really acts as a manifest, rather than a common file. Of course you could add stuff there, or even create an application.js.coffee for your common code. I decided to create a file called common.js.coffee (and in another case shared.js.coffee), which in my case was automatically handled by the require_tree . directive.
(Update based on comment from #jonathan-tran) In some cases, you may just want methods called on document ready for all pages -- for example, I used this to make a datepicker available to any field in any view. If, instead you want methods (actually global functions) available to be callable, you'll need to export the coffeescript functions to variables, for example by attaching to the window object. You can do both in a shared file.
It is true that if you use generators you'll end up with files for every controller which, if there's no specialized code result in a series of redundant $(document).ready -> statements when assets are compiled. So just get rid of the ones you don't use. But following the pattern of separating functionality specific to a page makes good sense to me and works well -- I know where to look to find stuff and that's worth a lot as a project grows.
And another rule I have learned with Rails: go with the flow. If that's how Rails does it, it's probably a good way. They do indeed think about these things. Don't fix what works :-)

Categories