Edge Animate: how to move javascript into html? - javascript

I need to create a self-contained html banner in Edge Animate. For this I have already encoded the images to base24. I just need to include the javascript into that html. When I publish my banner, Edge by default adds a 'edge_includes' folder which contains 'edge.6.0.0.min.js' and a javascript file in the same location as the html file which is called the same as the html file but with a '_edge.js' extention. Like for example 'text_edge.js'. Both .js files need to be moved to the published html file.
The 'edge.6.0.0.min.js' file I can move easily enough by moving it's script between the script tags of the html file which mentions that .js file.
The test_edge.js file however is more difficult. A typical published html file contains this amongst others:
<script> AdobeEdge.loadComposition('test', 'EDGE-102396420', {
scaleToFit: "none",
centerStage: "none",
minW: "0px",
maxW: "undefined",
width: "300px",
height: "250px" }, {"dom":{}}, {"dom":{}});
</script>
This is - I guess - where Edge loads that 'test_edge.js' file, through 'loadComposition'. But how can I copy the contents of that test_edge.js file into my html file then? I can't replace 'test' with the contents of 'test_edge.js' for example. Is there some other way to load that file's content into my html file? By coping it between script tags and making loadComposition load that scripted part instead of the external test_edge.js file for example?

It might be strange, but it should work if you just put the js inside the <script> tags. The header should look something like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<title>Untitled</title>
<!--Adobe Edge Runtime-->
<style>
.edgeLoad-EDGEK-472634723 { visibility:hidden; }
</style>
<script>
//Here goes the whole content from the test_edge.js
//Just ctrl+C and ctrl+V everything from it
</script>
<script>
//Here goes the whole content from the edge.6.0.0.min.js
//Just ctrl+C and ctrl+V everything from it
</script>
<script>
//Here goes the AdobeEdge.loadComposition stuff...
</script>
</head>
And also don't forget to create the class itself inside the <body> part
<div class="EDGE-102396420"></div>

Had a similar issue wanted to integrating js into one html, but I couldn't get it to work wihtout some tweaking in the edge runtime itself, so unfortunately it'll ruin the cdn speed adobe gives you. But otherwise the approach is similar to the answer given by #Klajbar.
If you make a check inside the edge runtime to can ensure compatibility with other files the requires edge runtime
What I did was to add a variable in loadComposition and then encapsulate the call which has f.load(a + "_edge.js") in a if statement to make sure is runs without the variable if need be.
Excerpt from modified edge.runtime.js example
//added inline as last variable
loadComposition: function(a, b, c, g, m,inline) {
function n(a, g) {
W(function() {
var m =
d("." + b),
k = /px|^0$/,
n = c.scaleToFit,
e = c.centerStage,
h = c.minW,
f = c.maxW,
l = c.width,
s = c.height,
y = m[0] || document.getElementsByTagName("body")[0];
"absolute" != y.style.position && "relative" != y.style.position && (y.style.position = "relative");
s && (y.style.height = s);
l && (y.style.width = l);
/^height$|^width$|^both$/.test(n) && (h = k.test(h) ? parseInt(h, 10) : void 0, f = k.test(f) ? parseInt(f, 10) : void 0, v(d(y), n, h, f, !1, c.bScaleToParent));
/^vertical$|^horizontal$|^both$/.test(e) && t(y, e);
a && L(H[b], null, a.dom, a.style, m[0], g + b);
m.removeClass("edgeLoad-" +
b)
})
}
/** removed some code here just for legibility **/
//if statement to override loading js files
if(!inline){
ba ? (window.edge_authoring_mode ||
(g ? (f.definePreloader(g), e()) : f.load(a + "_edgePreload.js", e)), a && (c && c.bootstrapLoading ? ka.push(a) : window.edge_authoring_mode && c.sym ? f.load(a +
"_edge.js?symbol=" + c.sym) : f.load(a + "_edge.js"))) : window.edge_authoring_mode ||
(m ? (f.defineDownLevelStage(m), h()) : f.load(a + "_edgePreload.js", h))
f.load(a + "_edge.js");
}
Once that's done you can include the code into the same html, where runtime is loaded first, then loadComposition block, then the _edge.js code.
Example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<title>Untitled</title>
<script>
//modified edge.runtime.js file
</script>
<style>
.edgeLoad-EDGE-24658395 { visibility:hidden; }
</style>
<script>
AdobeEdge.loadComposition('jem%26fix_afrens_930x180_uge14', 'EDGE-24658395', {
scaleToFit: "none",
centerStage: "none",
minW: "0px",
maxW: "undefined",
width: "930px",
height: "180px"
}, {"dom":{}}, {"style":{"${symbolSelector}":{"isStage":"true","rect":["undefined","undefined","960px","180px"]}},"dom":{}},true);
//notice appeded boolean value as the end to enable the override.
</script>
<!--Adobe Edge Runtime End-->
<script id="test">
// contents of _edge.js file
</script>
</head>
<body style="margin:0;padding:0;">
<div id="Stage" class="EDGE-24658395">
</div>
</body>
</html>
I just used it for loading just one _edge.js and haven't tested if you choose including the preloading stuff.

Just put you *_edge.js after runtime js.
In runtime js search for timeout function = 10 sec.
Change this to 0 sec, and runtime will start your animate at once load.
But you still will have error load *_edge.js in console. It is not so important.

Put absolute path of the folder where the test_edge.js file is present.
For example
test_edge.js file is under a/b/c folder then
<script> AdobeEdge.loadComposition('/a/b/c/test', 'EDGE-102396420', {
scaleToFit: "none",
centerStage: "none",
minW: "0px",
maxW: "undefined",
width: "300px",
height: "250px" }, {"dom":{}}, {"dom":{}});
</script>

Adobe Edge Embed js in html file
When you see edge html files. There are two js and images.
Both js are externally called. One is library and second is function called js ex.(728x90_edge.js)
Now, when upload all files in DFP type custom, then you use macro for 728x90_edge.js and all images src in this js.
Then how to use macro for images. That is challenge.
So you will have to embed this js in html. then you will use macro for images.
Follow the steps.
1, download liabrary js
remove below line in liabrary(edge.6.0.0.min.js), search after beautify
"_edge.js?symbol=" +
4.+ "_edge.js"
save and embed in html (<script type="text/javascript" src="edge.6.0.0.min - Copy.js"></script>)
cut all code from 728x90_edge.js and embed in html, after end of loadComposition function closing </script>
Now 728x90_edge.js will be empty, it's only use for loading.
use full name of file in AdobeEdge.loadComposition('728x90', 'EDGE-11479078', {
Ex. AdobeEdge.loadComposition('728x90_edge.js', 'EDGE-11479078', {
Now upload all files html, images and two js files.
Now you can use macro for two js file and images.
It's working on Local and DFP.

Related

Uncaught ReferenceError: $ is not defined - error in console [duplicate]

This question already has answers here:
Uncaught ReferenceError: $ is not defined?
(40 answers)
Closed 5 years ago.
I'm getting this error in my console, and it relates to a js script i'm using (Trumbowyg WYSIWYG: http://alex-d.github.io/Trumbowyg/)
Here's a picture of the browser console with the error:
When I click on (index):166, it shows this in the source:
id_content is the id for the WSYIWYG editor, and this is the required function in my js file to make it work:
$('#id_content').trumbowyg({
});
I've looked at other solutions and they say to load the jquery script before every other js script, but I'm already doing that and it doesn't solve anything. Does anyone have any idea what the problem is? By the way, I'm using this package to integrate it with django: https://github.com/sandino/django-trumbowyg, not sure if that changes anything. I just load the widget in my forms like this:
class PostForm(forms.ModelForm):
content = forms.CharField(widget=TrumbowygWidget(), required=False)
full html part:
< div >
< textarea
cols = "40"
id = "id_content"
name = "content"
rows = "10" >
< / textarea >
< script >
$("#id_content").trumbowyg({
lang: "en",
semantic: true,
resetCss: true,
autogrow: true,
removeformatPasted: true,
btnsDef: {
image: {
dropdown: ['upload', 'insertImage', 'base64', 'noembed'],
ico: 'insertImage'
}
},
btns: [
['formatting'],
'btnGrp-semantic',
['link'],
['image'],
'btnGrp-justify',
'btnGrp-lists',
'video',
['horizontalRule'],
['removeformat'],
['fullscreen'],
['viewHTML']
],
plugins: {
upload: {
serverPath: '/trumbowyg/upload_image/',
fileFieldName: 'image',
statusPropertyName: 'message',
urlPropertyName: 'file'
}
}
});
< / script >
< / div >
EDIT: keep in mind everything works fine, but I'm still getting this error. This is not a duplicate question, I've tried those solutions and none of them work.
end of the html file, scripts loading fine:
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-3.1.1.min.js"><\/script>')</script>
<script src="/static/js/jquery-jvectormap-2.0.3.min.js"></script>
<script src="http://jvectormap.com/js/jquery-jvectormap-world-mill.js"></script>
<script type="text/javascript" src="/static/js/base.js"></script>
<!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>-->
<script src="/static/js/Trumbowyg-master/dist/trumbowyg.js"></script>
</body>
It means your page does not have jQuery loaded.
Check network tab to see if jQuery had issues loading.
Or
Make sure that your code is being executed after jQuery in included.

Custom HTML element attribute not showing - Web-Components

I'm exploring web-components custom HTML elements, and I am running into a problem adding custom attributes to my custom elements: any value I set in the markup is never honored.
For a simple element like this, which should show the text supplied in the "flagtext" attribute, it does always show the default value.
<test-flag flagtext="my text"></test-flag>
Full JSBin sample is here.
The JSBin uses the Polymer library (as this is the only thing I can pull in there). I am using webcomponents.js generally, same result. Both in Chrome 49 and in Firefox 45 gives same result. There is no error showing in the console or debugger.
Every sample I find on the web has similar code but I tried various versions and it always refuses to update. I even copied a few samples into JSBin and they do not work either.
What could be wrong? I understand it is experimental technology but the consistency with which this isn't working is still surprising. Has this standard been abandoned? (I see that the latest April 2016 W3C draft of custom elements has entirely changed its approach.)
When I define "attributeChangedCallback" function, it does not fire.
I can easily modify the property via Javascript, this is not a problem.
But why can I not specify the property in markup, as I am supposed to?
Edit - full code
Note that you'll need to put these into separate files for the HTML import, and that you need the "webcomponents-lite.js" library.
Main HTML file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
test-flag
{
border: 1px solid blue;
}
</style>
</head>
<body>
<script src="lib/webcomponents-lite.min.js"></script>
<link rel="import" href="test-flag.html">
Here is the custom test-flag component:
<p>
<test-flag flagtext="my text"></test-flag>
</body>
</html>
File: test-flag.html
<template>
<style>
</style>
Content:
<div id="testflagID">
</div>
</template>
<script>
(function() {
var _currentScript = (document._currentScript || document.currentScript);
var importDoc = _currentScript.ownerDocument;
var customPrototype = Object.create(HTMLElement.prototype);
Object.defineProperty(customPrototype, 'flagtext', {value: '(default)', writable: true});
document.registerElement('test-flag', {prototype: customPrototype});
customPrototype.createdCallback = function()
{
var template = importDoc.querySelector('template');
var clone = document.importNode(template.content, true);
var idx = clone.querySelector("#testflagID");
idx.textContent = this.flagtext;
var root = this;
var createdElement = root.appendChild(clone);
};
})();
</script>
There are 2 concepts that are not automatically linked together.
In the HTML code:
<test-flag flagtext="my text"></test-flag>
...term flagtext is an HTML attribute (not a property).
In the JavaScript code:
Object.defineProperty(customPrototype, 'flagtext', {value: '(default)', writable: true})
...term flagtext is a JavaScript property (not an attribute).
For standard elements, the browser automatically binds the property value to the attribute value (and vice versa). For Custom Elements, too (with standard attributes). But if you want to add a custom attribute, you'll have to bind it manually.
For example, in the createdCallback() method, add:
this.flagtext = this.getAttribute( 'flagtext' ) || '(default)'
Live sample:
document.registerElement( 'test-flag' , {
prototype: Object.create( HTMLElement.prototype, {
flagtext: {
value: '(default)',
writable: true
},
createdCallback: {
value: function()
{
this.flagtext = this.getAttribute( 'flagtext' ) || this.flagtext
this.innerHTML = 'flagtext=' + this.flagtext
}
},
} )
} )
<test-flag flagtext='new content'>Hello</test-flag>
NB: the attributeChangedCallback() method is fired only when an attribute is changed after element creation (which is not the case here).

Typescript window.onload not being called after adding requirejs for phaser game

I am trying to make a game with phaser and Typescript. I followed the instructions here and it worked initialy. The problems came when I tried to modularise my code using AMD and requirejs
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Resonate</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="phaser.js"></script>
<script src="http://requirejs.org/docs/release/2.1.20/minified/require.js" data-main="app"></script>
</head>
<body>
<h1>RESONATE</h1>
<div id="content"></div>
</body>
</html>
Player.ts
export class Player {
color: string;
constructor() {
this.color = "#0000ff";
}
}
app.ts
import player = require("Player");
class PhaserDemo {
game: Phaser.Game;
constructor() {
this.game = new Phaser.Game(800, 600, Phaser.WEBGL, 'content', { preload: this.preload, create: this.create });
}
preload() {
this.game.load.image('phaser_run', 'run.png');
}
create() {
console.log("Before");
var p = new player.Player();
this.game.stage.backgroundColor = p.color;
}
}
window.onload = () => {
console.log("ONLOAD");
var game = new PhaserDemo();
};
Now when I load it up window.onload is never called, I tried following
window.onload not calling function
for the Javascript solution but I can't get it to work in typescript.
Also here is the generated Javascript if you want to take a look https://gist.github.com/koreus7/06bee4a30d22bdc76d62
for the Javascript solution but I can't get it to work in typescript.
Basically if the window is already loaded attaching to window.onload will not call the attached function.
Check for document.readyState === "complete". Alternatively use something like jquery ready : https://api.jquery.com/ready/
I believe it is caused by the require.js loader, it is without I explicitly know it a bit similar to jspm system.js , and so we don't need to ensure that the window is loaded because the loader already has ensured that.
I just removed the window.onload and it worked fine :)

How to use RPG.JS

I'm trying to work with this library (RPG.js) because it looks very powerfull, I looked at the official tutorial but i don't understand a lot of things, State 4 : "Initialize the canvas in your JS file :", whitch one ?
Is any one already used this library or know an other powerfull ?
Thanks for all.
Well, actually it was not so simple; I struggled I bit until I got a minimal functional game. What I did was not the "optimal" approach, but at least worked for me (I was using Mozilla Firefox in a Windows 7 OS). If someone knows how to improve what I did, I would be happy to know (since I'm a newbie in this library too), but since I was not able to find a good a simple starter tutorial in the net, I want to share what I did, in the hope I can help someone.
Before anything, create a HTML file, and call the libs inside the <head> tag:
<script src="canvasengine-X.Y.Z.all.min.js"></script>
<script src="rpgjs-X.Y.Z.min.js"></script>
And the canvas inside the <body> tag:
<canvas id="canvas_id" width="640" height="480"></canvas>
There's a 'sample' folder inside the github project (see https://github.com/RSamaium/RPG-JS), and inside this folder there is a functional game, and you can open it in the browser by the file quick.html. The idea is that if the sample game can work, then you can make your game work too, so I started trying to use the same graphics, data etc. of the sample.
First, you need to create in the root of your project the following folders and subfolders:
core
core\scene
Data
Data\Maps
Graphics
To have a minimal functional game, you need 1) a map to walk with your character, and 2) a character to control. So, you need to have graphics for some tiles to build your map and the walking model for your character. Create the subfolders below:
Graphics\Characters
Graphics\Tilesets
Graphics\Windowskins
And then copy the following files from the corresponding sample subfolder to these folders you created:
Graphics\Characters\event1.png
Graphics\Tilesets\tileset.png
Graphics\Windowskins\window.png #this file will be necessary for some of the js files below, even if not used; to remove this necessity, you'll need to edit these files - not what we want to do in the start.
In the 'core/scene' folder, you'll have some js files to load scenes (like the scene of your walking in the map, the gameover scene). I needed to copy all the js files inside the corresponding folder in the 'sample' project to the 'core/scene' folder of your game. This folder is not inside the 'sample' folder, but in the root of the github project. I only got my game working when I added all the 7 js files (without some work inside the codes you can remove the scenes you don't want, but since what we want is just to be able to run a simple game, let's copy them for now):
Scene_Gameover.js
Scene_Generated.js
Scene_Load.js
Scene_Map.js
Scene_Menu.js
Scene_Title.js
Scene_Window.js
Now, I added the following code inside a <script> tag on the html. This is more or less the same that was in the documentation. These codes will create an "actor" (a character), a "map", and the tiles you'll use in the map
For more details on maps or tiles, you should read the documentation (the same you linked in your question).
RPGJS.Materials = {
"characters": {
"1": "event1.png"
},
"tilesets": {
"1": "tileset.png"
}
};
RPGJS.Database = {
"actors": {
"1": {
"graphic": "1"
}
},
"tilesets": {
"1": {
"graphic": "1"
}
},
"map_infos": {
"1": {
"tileset_id": "1"
}
}
};
RPGJS.defines({
canvas: "canvas_id",
autoload: false
}).ready(function() {
RPGJS.Player.init({
actor: 1,
start: {x: 10, y: 10, id: 1} // Here, map id doesn't exist
});
RPGJS.Scene.map();
Lastly, create the json file setting every tile of your map. I just copied the MAP-1.json file from the 'sample' folder to inside the Data\Maps folder.
Then you'll be able to walk with your character in an empty map! Open the html file in your browser and try it!
Printscreen from the game running in a browser
Of course to have a real game you'll need to change a lot of this (as creating a database.json file and a materials.json file where you'll put most of the code you put in the <script> tag), but with the basics I hope you can work from that!
The tutorial is very clear
3. Add this code in your page :
<!DOCTYPE html>
<script src="canvasengine-X.Y.Z.all.min.js"></script>
<script src="rpgjs-X.Y.Z.min.js"></script>
<canvas id="canvas_id" width="640" height="480"></canvas>
That's "the canvas" ^
Brian Hellekin post a great tutorial. If you want see all the power of this library you must modify your html file in this way:
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script src="http://canvasengine.net/cdn/dev/canvasengine-latest.all.min.js"></script>
<script src="http://rpgjs.com/cdn/rpgjs-2.0.0.min.js"></script>
<script src="plugins/gamepad.js"></script>
<script src="plugins/virtualjoystick.js"></script>
<script src="plugins/soundmanager2-jsmin.js"></script>
<script>
var Data = null;
if (Data) {
Data.database._scenes = Data.menus;
Data.database.system = Data.settings;
}
RPGJS.defines({
canvas: "canvas",
plugins: ["/rpgjs/plugins/Hub", "/rpgjs/plugins/Arpg", "/rpgjs/plugins/MenuGenerated"],
scene_path: "/rpgjs/",
soundmanager: {
url: "/rpgjs/swf/",
},
autoload: Data == null,
ignoreLoadError: true
}).ready(function(rpg) {
var material_json = {};
var m, type;
if (Data) {
for (var i in Data.materials) {
m = Data.materials[i];
type = m['type'] + "s";
if (!material_json[type]) {
material_json[type] = {};
}
material_json[type][m['material_id']] = RPGJS_Canvas.Materials.getFilename(m['path'], true);
}
var m, e;
var map_info = Data.maps, info;
for (var id in Data.data_maps) {
m = Data.data_maps[id];
this.setMap(id, m.map.map);
info = map_info[id];
info.tileset_id = info.tileset;
info.autotiles_id = info.autotiles;
info.events = [];
info.dynamic_event = [];
for (var i=0 ; i < m.events.length ; i++) {
e = m.events[i];
if (e.data_event.type == "event" ) {
var format =
[
{
"id" : e.event_id,
"x" : e.position_x,
"y" : e.position_y,
"name" : 'EV-' + e.event_id
},
e.data_event.data.pages
];
this.setEvent(id, 'EV-' + e.event_id, format);
info.events.push('EV-' + e.event_id);
}
else {
var name, _id;
for(var key in e.data_event.data) {
_id = e.data_event.data[key];
name = key;
break;
}
info.dynamic_event.push({
"x" : e.position_x,
"y" : e.position_y,
"name" : name,
"id" : _id
});
}
}
}
Data.database.map_infos = map_info;
global.materials = material_json;
global.data = Data.database;
global.game_player.init();
}
var scene = this.scene.call("Scene_Title", {
overlay: true
});
scene.zIndex(0);
});
</script>
<style>
body {
padding: 0;
margin: 0;
overflow: hidden;
background: black;
}
canvas {
-webkit-user-select : none;
-moz-user-select : none;
overflow : hidden;
}
#font-face{
font-family : "RPG";
src : url("Graphics/Fonts/Philosopher-Regular.ttf");
}
#font-face{
font-family : "Megadeth";
src : url("Graphics/Fonts/Elementary_Gothic_Bookhand.ttf");
}
</style>
<div id="game">
<canvas id="canvas" width="640" height="480"></canvas>
</div>
Note:
/rpgjs/ is the folder where i put my project in my local server. For play the game i go to http://localhost/rpgjs/
For work you need to modify the JS file in /plugins/ directory.
/Hub/Sprite_Hub.js
use this path:
array.push(RPGJS.Path.getFile("pictures", "../Pictures/hub.png", "hub"));
array.push(RPGJS.Path.getFile("pictures", "../Pictures/hp_meter.png", "hp_meter"));
array.push(RPGJS.Path.getFile("pictures", "../Pictures/hp_number.png", "hp_number"));
array.push(RPGJS.Path.getFile("pictures", "../Pictures/Hero_Face.png", "hero_face"));
array.push(RPGJS.Path.getFile("pictures", "../Pictures/button_A.png", "button_a"));
array.push(RPGJS.Path.getFile("pictures", "../Pictures/button_B.png", "button_b"));
is very useful debug in the first time with developer tool of google chrome. When you see 404 error on a img resourse just go to your project and search the file name. Find what js script load it and fix path.
And not...the tutorial inside library project is not clear and isn't complete...they just want sell his rpgeditor and js library is put only for promotion purpose i think.
you can see here: http://rpgworld.altervista.org/rpgjs/ my final working project. Is just a try... but you can see the power of this library.
this demo load:
1- a welcome page with new and load came
2- a custom map with one event
3- a working event: a chest that if you open you will find 30 gold
4- a player manu: just click ESC button on keyboard
i don't know how use arpg plugin for a realtime combat event but i working on for understand of to use it.

Require.js nested requires

I'm trying to use requireJS but I want to build a hierarchy of dependencies: main requires obr.platcom and obr.platcom requires obr (for example).
I have this hierarchy of files:
- index.html
-> js
- main.js
-> lib
- jquery.js
- require.js
-> obr [my own 'libraries']
- obr.js
- obr.platcom.js
index.html
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<title>Platcom</title>
<script type="text/javascript" src="js/lib/jquery.js"></script>
<script data-main="js/main" src="js/lib/require.js"></script>
</head>
<body>
</body>
</html>
main.js
$(document).ready(function() {
require(["obr/obr.platcom"], function() {
obr.hola();
var myPlatcom = obr.platcom();
myPlatcom.test();
});
});
obr.js
var obr = {};
obr.hola = function() {
alert('Hola OBR');
};
obr.platcom.js
require(["obr.js"],function() {
obr.platcom = function(params) {
var that = {};
var test = function test() {
alert('Hola Platcom!');
}
that.test = test;
return that;
}
});
If I require both obr and obr.platcom files in the main all works, but if I use this nested style I receive the next error:
Uncaught ReferenceError: obr is not defined main.js:3
Do you know what I'm doing wrong?
Thank you in advance.
Alright, you've done several things wrong.
You need to specify as an argument the dependency you're injecting. For example, require(["obr/obr.platcom"], function() { won't do much unless you specify how the required module can be called. You should need this:
require(["obr/obr.platcom"], function( obr ) {
This way, you know in which variable your required object is.
The obr.js variables are in the global scope. You need to wrap them in a require or define function call. The following would work:
define(function() {
var obr = {};
obr.hola = function() {};
return obr;
});
You may have noticed some things that are wrong with your last file.
If you want your module to be imported somewhere, you have to define it. So you have to use the define function, not the require one. And the define function must return an object. Here is a fixed obr.platcom.js file:
// If you don't use "define" for the obr.js file too, this won't work
define(['obr'], function( obr ) {
obr.platcom = function() {};
// Don't forget to return the obr object, or the require of
// the main file won't return anything
return obr;
});
This way, things are done the correct way. Or at least, the way require.js wants you to do stuff.
I hope this reveals you how require.js can be effectively used to easily separate your code in modules :)

Categories