I am currently working on large projects that make use of lots of javascript files.
I then start learning of using local scopes and using objects.
What I do not really understand is how to call them into you local scope?
E.g if I create an object in an local scope in file-a, how can I use them as in a function in the document.ready scope file-b?
I get that you can find this online, but I get demotivation by the high amount of javascript on the internet and can't really find good examples or material. Any help?
Not sure,but I think you might be referring to the use of namespaces within JavaScript as a way to avoid adding all your functions to the main window object.
The Ugly Way
Let's assume you have 3 functions related to cats:
Function AddCat(cat) {
}
Function DeleteCat(catId) {
}
Function BreedCat(cat,cat) {
}
The way these items are coded, they are globally available. Not only does that clutter up your window object, it's hard to share data between these functions in a discreet way.
As long as this js file is loaded, any function in your app can call these functions just by calling AddCat()
Cleaner
To solve that problem, we could create a Cats object that acts as a "namespace" here:
Cats = {
AddCat: function(cat) {
},
DeleteCat: function(catId) {
},
BreedCat: function(cat,cat) {
}
}
Now, you've only added ONE object to the windows class: Cats. In addition, other methods in your web app can call any of those 3 items by calling Cats.AddCat() for example.
This lets you encapsulate all of the Cat data in your entire system within a single "namespace, so it's easier to read.
This can get a lot more detailed. By encapsulating items like this, you can start to hide variables that all your cat routines require from the rest of your code.
There is an excellent set of resources on this type of namespacing (including tons of detail) here and here with links that lead you deeper.
Is that what you were looking for?
Related
So I am trying to create a project with two canvas elements, each with its own paperscript, and with buttons on the outside of each that control certain functions within both.
Under the documentation under Paperscript, it says:
Please note:
When including more than one PaperScript in a page, each script will run >in its own scope and will not see the objects and functions declared in >the others. For PaperScript to communicate with other PaperScript or >JavaScript code, see the tutorial about PaperScript Interoperability.
... which is unfortunate because that tutorial reads as follows:
Coming very soon!
I've gotten stuck very quickly in this process. I've tried putting functions in global scope, calling them from outside their canvas, and seeing them print on the wrong canvas. I've tried exporting functions via a module and it seems to run the function (?!?!). And worst, the 'paper.projects' object is an array with one(!) project in it, the first canvas.
So I'm stumped.
Anyone know how to do this?
EDIT: So apparently there is this answer but I don't see how that gets me being able to call functions in the PaperScript scope from global scope scripts.
That just seems like a script to call global functions in the PaperScope, which doesn't work for me if I'm trying to make outside buttons do things.
Clearly I'm missing something.
SECOND EDIT: I have played around with various global functions, either in window.global or just sitting by themselves with no var declaration... but what seems to happen is that when I try to call a function which I have defined, say as:
globals.makecircle = function () {
var o = new Path.Circle({
radius: 50,
center: new Point (200,200)
})
}
in the main scope, it will just as soon run in the wrong window as the correct window. Also there is an incredible delay before it runs which I can't figure out.
THIRD EDIT: For clarity.
I have firstcanvas.js attached to canvas1 in my HTML, I have secondcanvas.js attached to canvas2. Both are referenced as paperscript type, as:
<script type="text/paperscript" src="scripts/firstcanvas.js" canvas="canvas1"></script>
<script type="text/paperscript" src="scripts/secondcanvas.js" canvas="canvas2"></script>
I create window.globals object as Jurg suggests. I call it from main.js with a button, such as:
window.globals = {}
`$('document').ready($('#dfs').on('click', window.globals.makecircle))`
I add this function to globals in firstcanvas.js as above.
If I have most recently clicked on canvas2, clicking on the button with id='DFS' will cause the function to run, extremely delayed, on canvas2.
And paper.projects does not list both projects, so I can't use the activate() functions.
Okay! SOLVED!!!
Here's how to reference/activate PaperScript-created scopes from the global scope. Although there is no user-accessible array of scopes (that I know of), PaperScope.get(id) will retrieve them. For some reason I find PaperScope.get(0) already populated, and my two canvas/PaperScript elements actually referring to scopes with ids 1 and 2.
Therefore:
pscope1 = PaperScope.get(1)
pscope2 = PaperScope.get(2)
Then, in any function where I want to do something on my first canvas:
pscope1.activate()
// cool paper.js graphics stuff
pscope1.view.update()
The last line is because paper.js won't automatically update a view that the user is not interacting with.
Thanks to Jurg Lehni for the hint to use .activate().
PS Make sure that your paperscript objects are created before using PaperScope.get. I used good 'ol JQuery $('document').ready() for this...
PPS Another little hit from Jurg Lehni himself: Inside a PaperScript, this will point to the current scope. You could use that and store it in the global object.
Helo Folks,
I am working on a view in couchdb. And, in the 'extract' list function, I'm trying to filter out some information using that view (myView). From the client that connects to couchdb, I want to do 1 major thing - show the results from the 'extract' list function. But, there are multiple other things that I want to perform on the results returned from the 'extract' function. One simple operation out of all the other operations is 'sum'. But, there are many other features like calculating median/standard deviation etc on the results of the 'extract' list function.
{
"_id": "_design/myDesigndoc",
"lists": {
"extract": "function(head, req){ ...*extract some info the view*: **myView** ...}",
"sum" : "function(head,req) {...**sum up all the values returned from the 'extract' function above**...}"
},
"views": {
"myView" : { "map" : "..." },
}
}
So, I'm stuck at one point:-
As the whole design doc is a Json and the function bodies are javascript, is there a way to call the 'extract' list function in other list functions like 'sum', 'median', 'standard deviation' etc ?
Reason I want to do this:-
All the other list functions: 'sum', 'standard deviation' etc expect the return value of 'extract' function as input. So, just making redundant copies of the code of extract function in other list functions is the last thing I would want to do.
Is there an alternate way to solve this:-
Yes, there is a way. I had thought that I'll use another view functions than 'myView' for all these functionalities and write the same 'map' function as that in 'myView' but, all these views will have separate 'reduce' functions for calculating 'sum', 'standard dev' etc.
But, the calculation of those views caused a lot of resource usage because those many views were getting created each time.
Could you guys provide a better solution than this?
Thanks
My first thought was to implement the views again with reduce functions to do the calculations but you say this is too resource intensive.. I wonder how often are the views used and if there is a heap of changes between accesses?
If they are just used to produce some statistics for reports or something and are rarely accessed that when they do there is a heap of changes it needs to make to the view indexes maybe you could look at running a script that regularly retrieves the views so it keeps the views up to date so when they are accessed they still respond relatively quickly.
This is something we have done with our all of our views in our production environment and it works quite well, I guess it depends on your infrastructure and how much data you are pumping through.
Something else to consider I am not sure if there is any difference/benefit to doing so but maybe the built in reduce functions may offer better performance than your self created ones
http://wiki.apache.org/couchdb/Built-In_Reduce_Functions
I am an ActionScript 3 developer who is just making his first way in building a large-scale JavaScript app.
So I understand modules and understand that AMD is a good pattern to use. I read about RequireJS and implemented it. However, what I still don't understand is how to achieve Cross-Module communication. I understand that there should be some kind of mediator...
I read articles and posts and still couldn't understand how to implement it simply.
Here is my code, simplified:
main.js
require(["Player", "AssetsManager"], function (player, manager) {
player.loadXML();
});
Player.js
define(function () {
function parseXml(xml)
{
// NOW HERE IS THE PROBLEM -- how do I call AssetsManager from here???
AssetsManager.queueDownload($(xml).find("prop").text());
}
return {
loadXML: function () {
//FUNCTION TO LOAD THE XML HERE, WHEN LOADED CALL parseXml(xml)
}
}
});
AssetsManager.js
define(function () {
var arrDownloadQueue = [];
return {
queueDownload: function(path) {
arrDownloadQueue.push(path);
}
}
});
Any "for dummies" help will be appreciated :)
Thank you.
To load up modules from another modules that you define(), you would simply set the first parameter as an array, with your module names in it. So let's say, in your code, you wanted to load Player.js into AssetsManager.js, you would simply include the string Player in the array.
This is simply possible because define's abstract implementation is equivalent to require, only that the callback passed to define expects a value to be returned, and that it will add a "module" to a list of dependencies that you can load up.
AssetsManager.js
define(['Player'], function (player) {
//... Your code.
});
However, if I can add to it, I personally prefer the use of require inside of the callback passed to define to grab the dependency that you want to load, instead of passing parameter to the callback.
So here's my suggestion:
define(['Player'], function () {
var player = require('Player');
});
And this is because it's much more in tune with CommonJS.
And this is how main.js would look like formatted to be more CommonJS-friendly:
require(["Player", "AssetsManager"], function () {
var player = require('Player');
var manager = require('AssetsManager');
player.loadXML();
});
But the CommonJS way of doing things is just a personal preference. My rationale for it is that the order in which you input the dependency names in the array might change at any time, and i wouldn't want to have to step through both the array and the parameters list.
Another rationale of mine (though, it's just pedantic), is that I come from the world of Node.js, where modules are loaded via require().
But it's up to you.
(This would be a reply to skizeey's answer, but I don't have enough reputation for that)
Another way of solving this problem without pulling in Player's AssetManager dependency via require is to pass the AssetManager instance that main.js already has around. One way of accomplishing this might be to make Player's loadXML function accept an AssetManager parameter that then gets passed to parseXml, which then uses it. Another way might be for Player to have a variable to hold an AssetManager which gets read by parseXml. It could be set directly or a function to store an AssetManager in the variable could be used, called say, setAssetManager. This latter way has an extra consideration though - you then need to handle the case of that variable not being set before calling loadXml. This concept is generally called "dependency injection".
To be clear I'm not advising this over using AMD to load it in. I just wanted to provide you with more options; perhaps this technique may come in handier for you when solving another problem, or may help somebody else. :)
i've been playing with MVC for a while now, but since the project i'm on is starting to get wind in its sails more and more people are added to it. Since i'm in charge of hacking around to find out some "best practice", i'm especially wary about the possible misuses of javascript and would like to find out what would be the best way to have our views and partial views play nicely with javascript.
For the moment, we're having code that looks like this (only simplified for example's sake)
<script type="text/javascript">
function DisableInputsForSubmit() {
if ($('#IsDisabled').is(':checked')) {
$('#Parameters :input').attr('disabled', true);
} else {
$('#Parameters :input').removeAttr('disabled');
}
}
</script>
<%=Html.SubmitButton("submit", Html.ResourceText("submit"), New With {.class = "button", .onclick = "DisableInputsForSubmit(); if ($('#EditParameters').validate().form()) {SetContentArea(GetHtmlDisplay('SaveParameters', 'Area', 'Controller'), $('#Parameters').serialize());} return false;"})%><%=Html.ResourceIcon("Save")%>
Here, we're saving a form and posting it to the server, but we disable inputs we don't want to validate if a checkbox is checked.
a bit of context
Please ignore the Html.Resource* bits, it's the resource management
helpers
The SetContentArea method wraps ajax calls, and GetHtmlDisplay
resolves url regarding an area,
controller and action
We've got combres installed that takes care of compressing, minifying
and serving third-parties libraries and what i've clearly identified as reusable javascript
My problem is that if somebody else defines a function DisableInputsForSubmit at another level (let's say the master page, or in another javascript file), problems may arise.
Lots of videos on the web (Resig on the design of jQuery, or Douglas Crockford for his talk at Google about the good parts of javascript) talk about using the namespaces in your libraries/frameworks.
So far so good, but in this case, it looks a bit overkill. What is the recommended way to go? Should i:
Create a whole framework inside a namespace, and reference it globally in the application? Looks like a lot of work for something so tiny as this method
Create a skeleton framework, and use local javascript in my views/partials, eventually promoting parts of the inline javascript to framework status, depending on the usage we have? In this case, how can i cleanly isolate the inline javascript from other views/partials?
Don't worry and rely on UI testing to catch the problem if it ever happens?
As a matter of fact, i think that even the JS code i've written that is in a separate file will benefit from your answers :)
As a matter of safety/best practice, you should always use the module pattern. If you also use event handlers rather than shoving javascript into the onclick attribute, you don't have to worry about naming conflicts and your js is easier to read:
<script type="text/javascript">
(function() {
// your button selector may be different
$("input[type='submit'].button").click(function(ev) {
DisableInputsForSubmit();
if ($('#EditParameters').validate().form()) {
SetContentArea(GetHtmlDisplay('SaveParameters', 'Area','Controller'), $('#Parameters').serialize());
}
ev.preventDefault();
});
function DisableInputsForSubmit() {
if ($('#IsDisabled').is(':checked')) {
$('#Parameters :input').attr('disabled', true);
} else {
$('#Parameters :input').removeAttr('disabled');
}
}
})();
</script>
This is trivially easy to extract into an external file if you decide to.
Edit in response to comment:
To make a function re-usable, I would just use a namespace, yes. Something like this:
(function() {
MyNS = MyNS || {};
MyNS.DisableInputsForSubmit = function() {
//yada yada
}
})();
I started creating a javascript file in Sublime Text with a few lines and a few functions, but over days passed the file was growing and growing and now it has around 600 lines with about 40 functions.
So I keep scrolling up and down for writing or reading code. And I think that that it's not a good workflow. How can i be more organized with javascript code. Is there a technique that professionals use for that, or a tool?
600 lines is not so much, yet. What you can do is namespace your code (separate it according to functionality). For example:
Lets say you have a js file with a bunch of functions
function formatDate(date){ ... }
function calcAge(birthdate){ ... }
function removeAccents(string){ ... }
function resizeImage(img){ ... }
... and many more ...
You can go ahead and separate functions by category, in this case we could group all the functions that deal with dates. All the ones that deal with strings and the ones that handle images.
// we create a global namespace, on main.js
var MyCoolProject = {};
// then we include string.js, and put all the string functions here
MyCoolProject.string = {
removeAccents: function(string){ ... }
};
// on date.js, we put all date functions
MyCoolProject.date = {
formatDate: function(date){ ... },
calcAge: function(birthdate){ ... }
};
// so on with image.js
MyCoolProject.img = {
resizeImage: function(date){ ... }
};
This way you have several smaller files that handle a specific kind of logic and you would call your functions like this:
function doSomethingAwesome(str){
var awesomeString = MyCoolProject.string.awesomize(str);
alert(awesomeString);
}
You also benefit by having more maintainable code and avoid collisions. Collisions happen when you include another script that happens to have a function with the same name as yours. If this happens, only the last included function will be executed. By namespacing your code you prevent this.
Keep in mind
You will have more files, this means more <script> tags in your html in which sometimes the order matters! You should eventually use build tools like grunt or gulp to concatenate and minimize all the js into one single scripts.js file. This way you have full control over your code during development. But once in production your site will make only one request for a js file which should make your site load faster.
Also, the namespacing method used here is my personal preference but in js you can achieve the same behavior through other patterns like prototypes, closures, commonjs, etc so you could research these and see which one fits your personal preference. There is not one better than the other, just one that will serve as a tool to make you build it faster and better.