creating closure compiler extern - javascript

I'm using a jQuery plug-in and Google Closure Compiler. The problem is that there's a bug in the plug-in when I add the URL of that plug-in into the compilation, the compilation fails. So I want to create an extern for that plug-in. Basically, I'm only using 1 object and 2 methods from the entire library; something like this:
var TheObject = $.plugin({...});
var SomeVar = TheObject.someName.otherName(SomeString, {
prop1: [...],
onError: function () {...}
});
TheObject.SomeMethod();
I looked at the doc on Google's website but it's written from a confusing "what-it-is" perspective and I need a simple "how-to" perspective on how to do this. What do I need to do to create an extern for what I have?
Thanks.

Here you go:
How to Write Closure-compiler Extern Files – Part 1 The Basics
jQuery Plugins and Closure-Compiler
I haven't had time to finish out the series on creating externs. If this isn't enough for your project, I'll revisit the topic.

So I've been struggling on and off with this question for a while and I've come up with a working solution for others who have a plug-in they want to use in their code with closure compiler: instead of doing an extern, just use strings, like this:
var TheObject = $['plugin']({...});
var SomeVar = TheObject['someName']['otherName'](SomeString, {
'prop1': [...],
'onError': function () {...}
});
TheObject['SomeMethod']();
That may not work for everybody but this worked for me and saved me a great deal of hassle in terms of writing an extern. I found the doc online to be very confusing: either written by techies who explain what things are, but now how to use them, or written in a professorial tone, with not many empirical examples. I hope this answer will help others.

Related

Creating library without encapsulation Javascript

I am very new in creation of libraries in javascript and encapsulations in javascript. I created very first library with the help of one or two tutorials from the web.
The example looks like the following,
<script>
var libs=[];
(function(libs){
function firstLibrary (){
this.initializeHoldings = function () {}
  this.myLibrary = function(){
    var _myLibraryObject = [{FirstName: 'Ibrahim', LastName: 'Shaikh', CompanyName: 'Plexitech'},
{FirstName: 'Nizam', LastName: 'Siddiqui', CompanyName: 'Neoquant'}];
    return _myLibraryObject;
  }
}
libs.customLibrary = firstLibrary;
})(libs);
let $ = new libs.customLibrary();
console.log($.myLibrary());
</script>
This is how my code looks,
now the confusions are,
1): What are the difference between libraries and encapsulations in
javascript?
2): How can I create library without encapsulating it in javascript?
3): Does encapsulation always create library?
Yes, I know it might be a silly question for some of you but many newbies might get confused on this.
1): What are the difference between libraries and encapsulations in javascript?
A "library" is a set of functions/classes. "Encapsulation" doesn't really have a meaning as a unit of code like "library." Wikipedia's short definitions of "encapsulation" are pretty good:
A language mechanism for restricting direct access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
As you can see, neither means anything like "library." But you would probably use encapsulation in parts of your library.
2): How can I create library without encapsulating it in javascript?
Probably, if you didn't have any data maintained by the library that you needed to prevent other code from using, and didn't need to combine data with methods.
3): Does encapsulation always create library?
No, not at all. They're largely unrelated terms and concepts.

Can you instantiate an Element object AND define attributes simultaneously?

This may seem like a silly question to some. The short background is; I am clinically diagnosed with OCD, I am thus very particular about the formatting and neatness of my code so I apologize in advance. This leads me to my question:
Is there a way in javascript to instantiate an object and define its attributes in a block? My goal might be somewhat analogous to how you'd see a JSON object/string
Here's some pseudocode/formatting:
var preElement = document.createElement('pre')
.className = "nodeResults";
.innerHTML = formattedResponse;
.style = "blahblah";
.anymoreAttributes = "stuff";
Inconsequential, I know. I just noticed I spent 30 minutes researching this instead of writing functional code. Downfall of OCD. SO please help me; Is this possible yes, or no?
Sincerely,
WastingTehTime
This is not doable unless you write a class wrapper to handle this kind of formatting, or use the jQuery library.
jQuery example:
var preElement = $(document.createElement('pre'))
.addClass("nodeResult")
.html(formattedResponse)
.css(jsonFormattedCSS)
jsFiddle example: http://jsfiddle.net/3h5kfv2j/
This can be implemented in vanilla javascript too, but you will need to find a library that does this or code it yourself.
Here is some sample code of a vanilla implementation I just made: http://jsfiddle.net/4n4w3uqr/

Strange javascript behaviour - error unless 'classes' are defined in correct order

I have a very strange problem with javascript and easel js.
I am using the easel.js library and am already fairly far into the construction of a project using it.
I am attempting to have a 'class' (I know they aren't technically classes in javascript but I will use this terminology for lack of a better word) inherit the Shape class from easel js, and then have another class inherit that. So it would be something like this:
easeljs.Shape --> MenuButton --> BuildingButton
The code I am using looks like this:
BuildingButton.prototype = Object.create(MenuButton.prototype);
BuildingButton.prototype.constructor = BuildingButton;
function BuildingButton(){
MenuButton.call(this);
}
MenuButton.prototype = Object.create(createjs.Shape.prototype);
MenuButton.prototype.constructor = MenuButton;
function MenuButton(){
createjs.Shape.call(this);
}
The problem is that I get the following error with this code:
Uncaught TypeError: undefined is not a function
easeljs-0.7.1.combined.js:8439
(line 8439 is pointing to the initialize() function in the Shape() constructor).
now here's the strange thing. If I change the order of the definitions so that the sub class is defined second and not first, it works fine!
MenuButton.prototype = Object.create(createjs.Shape.prototype);
MenuButton.prototype.constructor = MenuButton;
function MenuButton(){
createjs.Shape.call(this);
}
BuildingButton.prototype = Object.create(MenuButton.prototype);
BuildingButton.prototype.constructor = BuildingButton;
function BuildingButton(){
MenuButton.call(this);
}
This is very confusing as I can't seem to figure out why on earth this is happening. I could just make sure I define them in the correct order and leave it be, but I have all my 'classes' in different source files which are then strung together by grunt, which does so alphabetically.
Also, I feel like I may have a big gap in my knowledge of javascript (or maybe easel.js I'm not sure what exactly is causing this behaviour).
Thanks in advance for your help and I hope the question makes sense!
MenuButton.prototype = Object.create(createjs.Shape.prototype);
…
BuildingButton.prototype = Object.create(MenuButton.prototype);
These two statements have a clear dependency and need to be executed in the correct order (for the function declarations the order is irrelevant if placed in the same scope/file, but if in different files they need to be loaded in the correct order obviously).
I have all my 'classes' in different source files which are then strung together by grunt, which does so alphabetically
That's not a good idea. You should use some build tool/script that allows the declaration of dependencies.
Read this to clear things out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain
In first example you try to inherit from nothing, since MenuButton.prototype is not yet defined. To make it work just add MenuButton.prototype = new createjs.Shape.prototype(instead of Object.create() wich shouldn't be used anymore) to instantiate it first before you can you use it. Your first code is like you are willing to eat a banana before having one.

OOP - Is it better to call functions from within other functions, or to have one big controller?

I'm re-writing a fairly complex script that I created a few weeks ago. After showing it to a few people, they all agreed that I should break it up into smaller pieces (classes) that have a specific purpose, and SOLID object-oriented programming principles
As a self-taught programmer these concepts are pretty new to me, and I'm a little confused about how to best transfer data from one function/class to another. For instance, here is a simplified structure of what I'm building:
MY QUESTION IS:
Should I have a "controller" script that calls all of these functions/classes and passes the data around wherever necessary? Is this where I would put the for loop from the diagram above, even though it would work just as well as part of Function 1 which could then call Function 2?
Without a controller/service script you'll not be able to meet single responsibility principle in fact. Here's a high level design I'd implement if I were you.
FileRepository
Should expose a method to get a file. Let's name it GetFileById.
MongoDBRepository
Methods for CRUD operations. Such as SelectById, SelectByQuery, Update, Create, Delete.
Object creation logic
If your createNewObj logic is simple it would be enough to move it to your object contructor so that your code looks like that: var newObj = new MyObj(json[i]);
But if it's relatively complex maybe because you use some third party frameforks for validation or whatever you'd better create a factory. Then you could would look this way: var newObj = MyObjFactory.Create(json[i]);
Service/controller
Finally you'll need to implement controller/service object. Let's name it WorkService with a method DoWork which should handle all interactions between the repositories and other objects discribed above. Here's approximately DoWork should look like:
function DoWork(fileId){
var json = fileRepository.SelectById(fileId);
for(var i=0;i<json.length;i++){
var newObj = new MyObj(json[i]); // or calling factory method
var dbRecord = MongoDBRepository.SelectByQuery(newObj.name, newObj.date);
if(dbRecord){
MongoDBRepository.Update(newObj);
}
else{
MongoDBRepository.Create(newObj);
}
}
}
Please note it's just a javascript syntax pseudo-code. Your actual code might look absolutley different but it gives your a feeling of what kind of design your should have. Also I exmplicitly didn't create a repository objects inside DoWork method, think of the way to inject them so you meet Dependency inversion principle.
Hope it helps!

Emacs + js2-mode: disable indenting completely?

I'm using js2-mode for working with javascript in emacs and for the most part it's very useful. However, the indenting methods are terribly frustrating when working with jQuery, closures, and JSON... for instance, code that I wish to be indented like this:
var foo = jQuery('#mycontainer ul li').each(function(el){
var bar = el.html();
});
Turns out as:
var foo = jQuery('#mycontainer ul li').each(function(el){
var bar = el.html();
});
Is there a way I can just switch off all the indenting "helpers" and just have emacs insert N spaces when I hit the tab key? I know manual-indentation is a step backwards, but having readable code is, IMHO, more useful than a tool that doesn't work as expected.
Not a direct answer to your question, but here is a fork of js2-mode that has improved indenting.
One of the improvements is that your example code is indented the way you ask here.
I guess I will make this a full answer instead of a comment; espresso-mode is included with Emacs, and is designed to be a Javascript mode for Emacs (instead of a Javascript mode that happens to run inside of Emacs). It works like regular programming modes, and also happens to indent things the way you like.
Check out this solution, maps indentation function in js2-mode to partially use indentation from esresso-mode (now known as js-mode included in emacs 23.2 and newer):
http://mihai.bazon.net/projects/editing-javascript-with-emacs-js2-mode
Works exactly as I expect indentation in emacs to work and you still get the parsing awesomeness from js2-mode.
Have you tried new versions of js2-mode? It looks like there's a fix out: http://code.google.com/p/js2-mode/issues/detail?id=94
js2-mode supports "bounce" indenting; you can press tab multiple times to choose different likely indenting levels, so you might be able to get the effect you want that way:
(setq js2-bounce-indent-p t)
You can simply bind TAB to insert itself:
(add-hook 'js2-mode-hook 'my-js2-mode-hook)
(defun my-js2-mode-hook ()
(define-key js2-mode-map [tab] 'self-insert-command))
(But the better solution would, of course, be to find out why the mode thinks it needs so much indentation for anonymous functions, and fix it.)
One other alternative is js3-mode. It indents like this by default, but there seems to be some options that might enable you to tweak it for your liking.
var foo = jQuery('#mycontainer ul li').each(function(el){
var bar = el.html();
});

Categories

Resources