I will read/write a file with angular from/to my hdd. I normaly use node module "fs". Whats the best practice to combine this module with angular to use it in node webkit?
Thanks!
Edit: (can't use require in angular to load npm modules. any ideas?)
.service("WindowService", WindowService);
function WindowService() {
this.gui = require('nw.gui');
}
i wrote this example, if you had any questions as to how things are working? you may also want to check out this as well, which the former example uses to work outside of the browser.
but since the main question is regarding the error involving the require function, i will elaborate. require is a function implemented by the node runtime, it was added because there was no way initially built into js to import code from fileA to fileB. so when your in the browser you dont need to require anything, just make sure you have the file added to the html ie: <script src="my/file.js"></script>. but if you really want to do require in the browser, just use browserfy.
I have similar experiences to you. I usually wrap modules to services and use it as normal angular service with DI.
This makes code more readable and maintanable. Also, when you want to change node module, you are changing it in one place.
for your project, i will look to
socket.io > for broadcast websocket, and update your angular scope...
shokidar > better than FS, with less bug than fs
Related
I'm trying to use require js and angular js together. Referred to someone guides by googling:
http://marcoslin.github.io/angularAMD/#/home
http://www.sitepoint.com/using-requirejs-angularjs-applications/
Both guides seem to use angular, and angular-route and angular-amd, but I thought they were for other complicated purposes, so I only used "angular js" (so there is no shim in require.config()).
My main.js looks like this;
require.config({
paths: {
jquery : 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min',
'angular' : 'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min',
'class' : 'class',
'utility' : '../utility/utility',
},
deps: ['main1']
});
where deps: ['main1'] is the file to load right after require is defined as the first guide uses.
But I'm keep getting this error:
Error: $injector:modulerr
('UpdateApp' is the name of the app that I'm using in my project.)
And the webpage says that I get the error when I've forgotten to include the file with the defined module.
Not using deps: ['main1'] but using require(['angular'], function(){} and logging out angular.module('myApp',[]) logs Object nicely though. ... It seems like require(['angular'], function(angular) does not work but require(['angular'], function() works for me, and guides don't seem to tell me whether I should do the latter or the former.
I thought it would be as simple as adding angular js in paths, and loading it with require() or define() will work, but it's not...
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
Looking into your code, I can see that you clearly mis-understood about the concept of using requireJS and angular together. Either of the links you found are make by expert JS developers. Where both tried to combine angular and requireJS as simple as it could. So you need to accept the fact that it is complicated.
=> This is why I will not try to help you with some code. Because it will took lots of time and it will related with many topic which will not likely fit into a single question and answer on stackoverflow.
How do I use Require JS and Angular JS as simple as just using them together to print "hello world"?
At first I want to repeat it. This is nothing like simple work. For requireJS you need to at least have advanced knowledge about what called AMD and able to imagine how things happen asynchronusly when requireJS trying to load an JS library.
Secondly, common knowledge about angular module/service injeaction. Since both requireJS and angular can do some sort of module/service injection you need to know about the difference between these two.
Third, the initial stage of your webapp. Since both requireJS and angular need to be initialled to run properly. So this will also the requirement.
Sum up
You will NOT able to understand both in a day or two. It will take time. But fortunately I have a couple of suggestions for you.
Research some about how requireJS and angular load their depenencies.
Go for angularAMD get the project seed. Set it up, run it, play with it.
Improve your knowledge about the initial state of both.
...
Profit!
P.S. just FYI. An year ago, I started with requireJS and angular. And I got hitted up with a big wall of knowleges, just like you. And these are what I have tried to understand them. Take your time, it is not like using jquery which can learn in a day or two. Even for some JS expert it took months just for them to confident about angular (not counting combine it with requireJS). Cheers!
Inside your main1.js you must be use require(['angular'], function(){} to start your application.
Require JS will give you a package dependency manager, concatenator/uglifier, javascript file loader, and an injector. Require JS injectors are used for injecting classes versus Angular, which is used to inject instances.
The big advantage is that RequireJS is going to speed up your application by managing your load and runtime dependencies. It's useful for big SPA's.
You can set up your file structure by defining all of your dependencies using "define". For functions to execute, you will need to use "require".
Here is a helpful video:
https://www.youtube.com/watch?v=4yulGISBF8w&index=1&list=PLgVbnDyASc1qDAam3Fe0f-u6u9MYL6pC8
I like keeping my javascript files as small as possible and using an architectural pattern. This usually means splitting my js files in Services, Controllers, Models, Views, etc.
Meteor automatically loads all js files. However every variable defined in any js file is processed as a local variable for that file. To be able to access them I have to define them like so:
//global
my_global_function = function(){
}
//not global
var my_global_function = function(){
}
//not global
function my_global_function(){
}
Defining a variable/function without the keyword var or function is not good practice. What are the possible alternatives?
The best option is to use ES2015 modules.
Meteor does not support modules natively yet, but there are packages that bring this support.
For example, universe:modules.
With modules you can import and export some variables/functions/classes/etc:
// module1.import.js
import alertSomething from './module2'
Meteor.startup(() => {
alertSomething();
});
// module2.import.js
export default function alertSomething() {
alert('something');
}
universe:modules is not the only solution, there are other similar projects. I love this one specially https://github.com/thereactivestack/kickstart-simple. It replaces Meteor's build system with WebPack's and enables hot-reloading if you use React.
UPDATE:
Meteor does support ES6 modules now
Since you seem very interested in proper architectural design, I would recommend looking at Meteor packages. Essentially, you have to declare any globally exposed variable in the package.js configuration, which is what you want: as little "leakage" as possible. Within a package, you can afford to be a little bit more sloppy, but you can still use var (and the absence of var) for more fine-grained control within a package. This can be done within Meteor right now.
You can find most information in the package documentation. The easiest way to get started is to create a package using meteor create --package [package-name]. This sets up a basic structure to play with. The api.export function is what controls exposed variables. See doc here.
Additionally, be careful with adding an unnecessary layer on top of the intrinsic Meteor architectural design. Templates are views, server side methods are services, etc. There are only some things that you don't get out of the box, so usually you'll add something like Astronomy or SimpleSchema.
Adding too much of your own architecture is probably going to end with you fighting the Meteor framework itself...
I'm trying to update the javascript on a large scale, php/codeigniter based website. It has many, many php partials for code being loaded onto certain pages, but only one footer, header. Most of the partials have inline script tags in them for loading javascript. This needs to be fixed and because the site is very modular with components being used multiple times across pages, require.js seems like a pretty good solution.
So, it's instantiate javascript, we typically do this.
<script type="javascript" src="../js/scriptname.js">
<script type="javascript">
DP.scriptname.init(parameters)
</script>
I'd like to get away from this and just have a have a single entry point for the js using require.
My question is this: what's the best way to instantiate javascript for certain pages using require? Do I need I need to continue including my scripts in the partial and then do something like writing a require module for that specific page and then wrap it all in my data-main script like this? We're planning on using Backbone and Marionette as well, but I won't be able to use the Backbone router to do anything like setting hash URLs. Should I use the URLs to instantiate my require modules perhaps?
Ok, hope someone can help. My experience has typically been in building single page websites. This is different. Thanks
Cam
Well, if I understand your question correctly, you can use Require JS in such way.
First of all, write a config in which you can describe mapping between module names and concrete files. For example:
requirejs.config({
baseUrl: 'js/modules' // by default load any module using this path
});
After that you should refactor your existing module and adjust it to the AMD format (see http://requirejs.org/docs/whyamd.html)
As a result of this step you will have something like this (let's say in file 'js/modules/scriptname.js'):
// module has the same name as the file, which contains it - "scriptname"
define(function () {
// define the module value by returning a value
return function () {};
});
And as a final step you can refactor your inline script and use this module in such way:
<script type="javascript">
// when we place name of the module as a first argument of the "define"
// function, Require JS find file that contains it and load it asynchronously
define(["scriptname"], function (scriptname) {
// "scriptname" now contains value that we recieve from the module definition
scriptname.init(parameters);
});
</script>
Hope this helps.
Note. My solution based on this section of official Require JS documentation: http://requirejs.org/docs/api.html#jsfiles
This question seems to come up a lot, so I'll point you to some resources that may help:
How does RequireJS work with multiple pages and partial views? - https://stackoverflow.com/a/10816983/617615
Modular HTML components with RequireJS - http://simonsmith.io/modular-html-components-with-requirejs/
Example RequireJS-based project that has multiple pages that share a common set of modules - https://github.com/requirejs/example-multipage
I'm new to Dojo so I don't quite understand all of Dojo's features. Here are some questions, but I'm sure some of them seem really stupid since I don't quite get how Dojo is structured yet:
How do you create multiple modules within a single js file and access the module in the file it's created? Also, how do you access specific modules from a file containing multiple modules?
What is the difference between require and define?
I successfully required a module from a file, but I can't figure out how to get the variables out of the file, how do you do this?
I was looking at how Dojo required its modules and notice that it does a http request for each file, but isn't that really inefficient when you're dealing with lots of modules and/or on a large site, you really would like to minimize the number of http requests necessary? What's the way around this?
Reading through The Dojo Loader will provide answers.
Basically module = file and very often (as a matter of best practice) module = file = class (more precisely public class defined via dojo/_base/declare).
Ad #4: You will need to employ The Dojo Build System, that will resolve all the dependencies and put all your modules into a single file (or more files, this depends on your build profile). Have a look at Dojo Boilerplate project, it may help with building your application.
How do you create multiple modules within a single js file?
While this is possible to do, and is done by the build system when it creates layer files, it is not recommended. Putting multiple modules in a single file means you have to use a different form of define that gives an explicit ID to eahc of them. This is less flexible then having the module IDs automatically derived from the file name and path (this, together with relative paths makes it much easier to move and rename AMD modules, compared to old-style modules)
What is the difference between require and define?
define is a beefed up version of require that defines a new module with its return value.
I successfully required a module from a file, but I can't figure out how to get the variables out of the file.
I am not sure wha toyu mean with this (without giving a concrete runnable example) but all you have to do is create an object to be the value of your module and return it from define. This is not very far off from how you would define modules the old way, with manual "namespaces"
//foo.js
define([], function(){
var M = {}; //the exported stuff will go here
var myVariable = 16; //private function variables are private (like they are everywhere else)
//and cannot be seen from the outside
M.anumber = myvariable + 1; //things on the returned object can be seen from the outside
return M; //people who require this module will get this return value
});
//bar.js
define(['foo'], function(foo){
console.log( foo.anumber );
});
I was looking at how Dojo required its modules and notice that it does a http request for each file...
As phusick pointed out, the build system can be used to bundle all the modules into a single file (giving you the best of both worlds - modularity during development and performance during deployment). It can also do other cool stuff, like bundling CSS and passing the Javascript through a minifier or through the Closure compiler, checking ifdef for creating platform-dependent builds, etc.
I'm shipping socket.io as part of my code for 3rd party sites to use. I don't want it to pollute the global namespace (e.g. different versions of io will collide) but rather make it work only as part of my library, So it will be namespaced and called only from
MyLibrary.io
How do I go about this?
Since you have total control over the file, then the easiest thing to do would be to just modify the file to load socket.io at a new location.
The easiest way I would say to do that would be to wrap the contents of dist/socket.io.js with
(function() {
// All Standard SocketIO code
}).call(MyLibrary);
That will make the file load io onto MyLibrary instead. SocketIO, like many libraries, uses this to decide how to load things. In a browser circumstance, this is the object window, but by wrapping a function around everything, you can control this and change it to your own value by using the method call.
Many other libraries, though not socketIO, have a helper to avoid exactly this problem. Often they have a method called noConflict(). For example, if you wanted to avoid a problem like this for jQuery, you could do:
MyLibrary.$ = MyLibrary.jQuery = jQuery.noConflict(true);
That works because when jQuery loads, it saves a reference to the previously loaded version, so that if it needs to, it can set the global objects back to how they were.
It seems that the suggested way to do this (Issue #85) is to load it as per normal then run these two lines:
MyLibrary.io = window.io; // Assign it to your desired namespace
delete window.io; // Remove it from the window namespace
The code in socket.io.js only adds the io variable to the window.
You could modify the code in socket.io.js but that might make it hard to maintain in the future since you would have to track changes you make to that file and propagate them into newer versions of socket.io.js.
At first, I thought you could do something with module.exports since it had the CommonJS format, however, after reading the code, I realized it's just the way things were organized before building the socket.io.js file. See the file directory here for what I'm referring to.