1&&(p=o.slice(1)),l.publish(a,p)});var a=function(a,b){n[a]=b},b=function(a){var b=[];return n[a]&&(b=n[a]),b};return{addModule:function(b,c,d){a(b,d),j.listenEvent(b,"onError",function(a,c){yOSON.Log("The module '"+b+"' has an error: "+c+"(): "+a.message)}),j.addModule(b,c)},runModule:function(a,c){var d=j.getModule(a);if(d){var e=b(a);m.inQueue(function(b){k.ready(e,function(){j.runModule(a,c),b()},function(){yOSON.Log("Error: the module "+a+" can't be loaded"),b()})})}else yOSON.Log("Error: the module "+a+" don't exists")},getModuleFunctions:function(a){var b=j.getModule(a);return definition=b.moduleDefinition(),void 0===definition.init?(yOSON.Log("Error: the module "+a+" don't have any functions to test"),{}):definition.tests},setStaticHost:function(a){k.setStaticHost(a)},setVersionUrl:function(a){k.setVersionUrl(a)}}}(),yOSON}();
3 | //# sourceMappingURL=yoson.min.map
4 |
--------------------------------------------------------------------------------
/config/build.js:
--------------------------------------------------------------------------------
1 | var require = {
2 | baseUrl: './src',
3 | paths:{
4 | 'base':'./core/base',
5 | }
6 | };
7 |
--------------------------------------------------------------------------------
/config/test.js:
--------------------------------------------------------------------------------
1 | var require = {
2 | baseUrl: './src',
3 | paths:{
4 | 'spec':'spec',
5 | 'base':'./core/base',
6 |
7 | 'jquery':'../test/lib/jquery',
8 |
9 | 'sinon':'../lib/sinon',
10 | 'jasmine':'../lib/jasmine-1.3.1/jasmine',
11 | 'jasmine-html':'../lib/jasmine-1.3.1/jasmine-html',
12 | 'jasmine-jquery':'../lib/jasmine-jquery'
13 | },
14 | shim:{
15 | 'jasmine':{
16 | exports:'jasmine'
17 | },
18 | 'sinon':{
19 | exports:'sinon'
20 | },
21 | 'jasmine-html':['jasmine'],
22 | 'jasmine-jquery':[ 'jasmine' ]
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/docs/api.js:
--------------------------------------------------------------------------------
1 | YUI.add("yuidoc-meta", function(Y) {
2 | Y.YUIDoc = { meta: {
3 | "classes": [
4 | "Dependency",
5 | "DependencyManager"
6 | ],
7 | "modules": [],
8 | "allModules": []
9 | } };
10 | });
--------------------------------------------------------------------------------
/docs/assets/css/external-small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/docs/assets/css/external-small.png
--------------------------------------------------------------------------------
/docs/assets/css/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/docs/assets/css/logo.png
--------------------------------------------------------------------------------
/docs/assets/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/docs/assets/favicon.png
--------------------------------------------------------------------------------
/docs/assets/img/spinner.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/docs/assets/img/spinner.gif
--------------------------------------------------------------------------------
/docs/assets/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Redirector
5 |
6 |
7 |
8 | Click here to redirect
9 |
10 |
11 |
--------------------------------------------------------------------------------
/docs/assets/js/api-filter.js:
--------------------------------------------------------------------------------
1 | YUI.add('api-filter', function (Y) {
2 |
3 | Y.APIFilter = Y.Base.create('apiFilter', Y.Base, [Y.AutoCompleteBase], {
4 | // -- Initializer ----------------------------------------------------------
5 | initializer: function () {
6 | this._bindUIACBase();
7 | this._syncUIACBase();
8 | },
9 | getDisplayName: function(name) {
10 |
11 | Y.each(Y.YUIDoc.meta.allModules, function(i) {
12 | if (i.name === name && i.displayName) {
13 | name = i.displayName;
14 | }
15 | });
16 |
17 | return name;
18 | }
19 |
20 | }, {
21 | // -- Attributes -----------------------------------------------------------
22 | ATTRS: {
23 | resultHighlighter: {
24 | value: 'phraseMatch'
25 | },
26 |
27 | // May be set to "classes" or "modules".
28 | queryType: {
29 | value: 'classes'
30 | },
31 |
32 | source: {
33 | valueFn: function() {
34 | var self = this;
35 | return function(q) {
36 | var data = Y.YUIDoc.meta[self.get('queryType')],
37 | out = [];
38 | Y.each(data, function(v) {
39 | if (v.toLowerCase().indexOf(q.toLowerCase()) > -1) {
40 | out.push(v);
41 | }
42 | });
43 | return out;
44 | };
45 | }
46 | }
47 | }
48 | });
49 |
50 | }, '3.4.0', {requires: [
51 | 'autocomplete-base', 'autocomplete-highlighters', 'autocomplete-sources'
52 | ]});
53 |
--------------------------------------------------------------------------------
/docs/assets/js/api-list.js:
--------------------------------------------------------------------------------
1 | YUI.add('api-list', function (Y) {
2 |
3 | var Lang = Y.Lang,
4 | YArray = Y.Array,
5 |
6 | APIList = Y.namespace('APIList'),
7 |
8 | classesNode = Y.one('#api-classes'),
9 | inputNode = Y.one('#api-filter'),
10 | modulesNode = Y.one('#api-modules'),
11 | tabviewNode = Y.one('#api-tabview'),
12 |
13 | tabs = APIList.tabs = {},
14 |
15 | filter = APIList.filter = new Y.APIFilter({
16 | inputNode : inputNode,
17 | maxResults: 1000,
18 |
19 | on: {
20 | results: onFilterResults
21 | }
22 | }),
23 |
24 | search = APIList.search = new Y.APISearch({
25 | inputNode : inputNode,
26 | maxResults: 100,
27 |
28 | on: {
29 | clear : onSearchClear,
30 | results: onSearchResults
31 | }
32 | }),
33 |
34 | tabview = APIList.tabview = new Y.TabView({
35 | srcNode : tabviewNode,
36 | panelNode: '#api-tabview-panel',
37 | render : true,
38 |
39 | on: {
40 | selectionChange: onTabSelectionChange
41 | }
42 | }),
43 |
44 | focusManager = APIList.focusManager = tabviewNode.plug(Y.Plugin.NodeFocusManager, {
45 | circular : true,
46 | descendants: '#api-filter, .yui3-tab-panel-selected .api-list-item a, .yui3-tab-panel-selected .result a',
47 | keys : {next: 'down:40', previous: 'down:38'}
48 | }).focusManager,
49 |
50 | LIST_ITEM_TEMPLATE =
51 | '' +
52 | '{displayName} ' +
53 | ' ';
54 |
55 | // -- Init ---------------------------------------------------------------------
56 |
57 | // Duckpunch FocusManager's key event handling to prevent it from handling key
58 | // events when a modifier is pressed.
59 | Y.before(function (e, activeDescendant) {
60 | if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
61 | return new Y.Do.Prevent();
62 | }
63 | }, focusManager, '_focusPrevious', focusManager);
64 |
65 | Y.before(function (e, activeDescendant) {
66 | if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
67 | return new Y.Do.Prevent();
68 | }
69 | }, focusManager, '_focusNext', focusManager);
70 |
71 | // Create a mapping of tabs in the tabview so we can refer to them easily later.
72 | tabview.each(function (tab, index) {
73 | var name = tab.get('label').toLowerCase();
74 |
75 | tabs[name] = {
76 | index: index,
77 | name : name,
78 | tab : tab
79 | };
80 | });
81 |
82 | // Switch tabs on Ctrl/Cmd-Left/Right arrows.
83 | tabviewNode.on('key', onTabSwitchKey, 'down:37,39');
84 |
85 | // Focus the filter input when the `/` key is pressed.
86 | Y.one(Y.config.doc).on('key', onSearchKey, 'down:83');
87 |
88 | // Keep the Focus Manager up to date.
89 | inputNode.on('focus', function () {
90 | focusManager.set('activeDescendant', inputNode);
91 | });
92 |
93 | // Update all tabview links to resolved URLs.
94 | tabview.get('panelNode').all('a').each(function (link) {
95 | link.setAttribute('href', link.get('href'));
96 | });
97 |
98 | // -- Private Functions --------------------------------------------------------
99 | function getFilterResultNode() {
100 | return filter.get('queryType') === 'classes' ? classesNode : modulesNode;
101 | }
102 |
103 | // -- Event Handlers -----------------------------------------------------------
104 | function onFilterResults(e) {
105 | var frag = Y.one(Y.config.doc.createDocumentFragment()),
106 | resultNode = getFilterResultNode(),
107 | typePlural = filter.get('queryType'),
108 | typeSingular = typePlural === 'classes' ? 'class' : 'module';
109 |
110 | if (e.results.length) {
111 | YArray.each(e.results, function (result) {
112 | frag.append(Lang.sub(LIST_ITEM_TEMPLATE, {
113 | rootPath : APIList.rootPath,
114 | displayName : filter.getDisplayName(result.highlighted),
115 | name : result.text,
116 | typePlural : typePlural,
117 | typeSingular: typeSingular
118 | }));
119 | });
120 | } else {
121 | frag.append(
122 | '' +
123 | 'No ' + typePlural + ' found.' +
124 | ' '
125 | );
126 | }
127 |
128 | resultNode.empty(true);
129 | resultNode.append(frag);
130 |
131 | focusManager.refresh();
132 | }
133 |
134 | function onSearchClear(e) {
135 |
136 | focusManager.refresh();
137 | }
138 |
139 | function onSearchKey(e) {
140 | var target = e.target;
141 |
142 | if (target.test('input,select,textarea')
143 | || target.get('isContentEditable')) {
144 | return;
145 | }
146 |
147 | e.preventDefault();
148 |
149 | inputNode.focus();
150 | focusManager.refresh();
151 | }
152 |
153 | function onSearchResults(e) {
154 | var frag = Y.one(Y.config.doc.createDocumentFragment());
155 |
156 | if (e.results.length) {
157 | YArray.each(e.results, function (result) {
158 | frag.append(result.display);
159 | });
160 | } else {
161 | frag.append(
162 | '' +
163 | 'No results found. Maybe you\'ll have better luck with a ' +
164 | 'different query?' +
165 | ' '
166 | );
167 | }
168 |
169 |
170 | focusManager.refresh();
171 | }
172 |
173 | function onTabSelectionChange(e) {
174 | var tab = e.newVal,
175 | name = tab.get('label').toLowerCase();
176 |
177 | tabs.selected = {
178 | index: tab.get('index'),
179 | name : name,
180 | tab : tab
181 | };
182 |
183 | switch (name) {
184 | case 'classes': // fallthru
185 | case 'modules':
186 | filter.setAttrs({
187 | minQueryLength: 0,
188 | queryType : name
189 | });
190 |
191 | search.set('minQueryLength', -1);
192 |
193 | // Only send a request if this isn't the initially-selected tab.
194 | if (e.prevVal) {
195 | filter.sendRequest(filter.get('value'));
196 | }
197 | break;
198 |
199 | case 'everything':
200 | filter.set('minQueryLength', -1);
201 | search.set('minQueryLength', 1);
202 |
203 | if (search.get('value')) {
204 | search.sendRequest(search.get('value'));
205 | } else {
206 | inputNode.focus();
207 | }
208 | break;
209 |
210 | default:
211 | // WTF? We shouldn't be here!
212 | filter.set('minQueryLength', -1);
213 | search.set('minQueryLength', -1);
214 | }
215 |
216 | if (focusManager) {
217 | setTimeout(function () {
218 | focusManager.refresh();
219 | }, 1);
220 | }
221 | }
222 |
223 | function onTabSwitchKey(e) {
224 | var currentTabIndex = tabs.selected.index;
225 |
226 | if (!(e.ctrlKey || e.metaKey)) {
227 | return;
228 | }
229 |
230 | e.preventDefault();
231 |
232 | switch (e.keyCode) {
233 | case 37: // left arrow
234 | if (currentTabIndex > 0) {
235 | tabview.selectChild(currentTabIndex - 1);
236 | inputNode.focus();
237 | }
238 | break;
239 |
240 | case 39: // right arrow
241 | if (currentTabIndex < (Y.Object.size(tabs) - 2)) {
242 | tabview.selectChild(currentTabIndex + 1);
243 | inputNode.focus();
244 | }
245 | break;
246 | }
247 | }
248 |
249 | }, '3.4.0', {requires: [
250 | 'api-filter', 'api-search', 'event-key', 'node-focusmanager', 'tabview'
251 | ]});
252 |
--------------------------------------------------------------------------------
/docs/assets/js/api-search.js:
--------------------------------------------------------------------------------
1 | YUI.add('api-search', function (Y) {
2 |
3 | var Lang = Y.Lang,
4 | Node = Y.Node,
5 | YArray = Y.Array;
6 |
7 | Y.APISearch = Y.Base.create('apiSearch', Y.Base, [Y.AutoCompleteBase], {
8 | // -- Public Properties ----------------------------------------------------
9 | RESULT_TEMPLATE:
10 | '' +
11 | '' +
12 | '{name} ' +
13 | '{resultType} ' +
14 | '{description}
' +
15 | '{class} ' +
16 | ' ' +
17 | ' ',
18 |
19 | // -- Initializer ----------------------------------------------------------
20 | initializer: function () {
21 | this._bindUIACBase();
22 | this._syncUIACBase();
23 | },
24 |
25 | // -- Protected Methods ----------------------------------------------------
26 | _apiResultFilter: function (query, results) {
27 | // Filter components out of the results.
28 | return YArray.filter(results, function (result) {
29 | return result.raw.resultType === 'component' ? false : result;
30 | });
31 | },
32 |
33 | _apiResultFormatter: function (query, results) {
34 | return YArray.map(results, function (result) {
35 | var raw = Y.merge(result.raw), // create a copy
36 | desc = raw.description || '';
37 |
38 | // Convert description to text and truncate it if necessary.
39 | desc = Node.create('' + desc + '
').get('text');
40 |
41 | if (desc.length > 65) {
42 | desc = Y.Escape.html(desc.substr(0, 65)) + ' …';
43 | } else {
44 | desc = Y.Escape.html(desc);
45 | }
46 |
47 | raw['class'] || (raw['class'] = '');
48 | raw.description = desc;
49 |
50 | // Use the highlighted result name.
51 | raw.name = result.highlighted;
52 |
53 | return Lang.sub(this.RESULT_TEMPLATE, raw);
54 | }, this);
55 | },
56 |
57 | _apiTextLocator: function (result) {
58 | return result.displayName || result.name;
59 | }
60 | }, {
61 | // -- Attributes -----------------------------------------------------------
62 | ATTRS: {
63 | resultFormatter: {
64 | valueFn: function () {
65 | return this._apiResultFormatter;
66 | }
67 | },
68 |
69 | resultFilters: {
70 | valueFn: function () {
71 | return this._apiResultFilter;
72 | }
73 | },
74 |
75 | resultHighlighter: {
76 | value: 'phraseMatch'
77 | },
78 |
79 | resultListLocator: {
80 | value: 'data.results'
81 | },
82 |
83 | resultTextLocator: {
84 | valueFn: function () {
85 | return this._apiTextLocator;
86 | }
87 | },
88 |
89 | source: {
90 | value: '/api/v1/search?q={query}&count={maxResults}'
91 | }
92 | }
93 | });
94 |
95 | }, '3.4.0', {requires: [
96 | 'autocomplete-base', 'autocomplete-highlighters', 'autocomplete-sources',
97 | 'escape'
98 | ]});
99 |
--------------------------------------------------------------------------------
/docs/assets/js/yui-prettify.js:
--------------------------------------------------------------------------------
1 | YUI().use('node', function(Y) {
2 | var code = Y.all('.prettyprint.linenums');
3 | if (code.size()) {
4 | code.each(function(c) {
5 | var lis = c.all('ol li'),
6 | l = 1;
7 | lis.each(function(n) {
8 | n.prepend(' ');
9 | l++;
10 | });
11 | });
12 | var h = location.hash;
13 | location.hash = '';
14 | h = h.replace('LINE_', 'LINENUM_');
15 | location.hash = h;
16 | }
17 | });
18 |
--------------------------------------------------------------------------------
/docs/assets/vendor/prettify/CHANGES.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Change Log
5 |
6 |
7 | README
8 |
9 | Known Issues
10 |
11 | Perl formatting is really crappy. Partly because the author is lazy and
12 | partly because Perl is
13 | hard to parse.
14 | On some browsers, <code>
elements with newlines in the text
15 | which use CSS to specify white-space:pre
will have the newlines
16 | improperly stripped if the element is not attached to the document at the time
17 | the stripping is done. Also, on IE 6, all newlines will be stripped from
18 | <code>
elements because of the way IE6 produces
19 | innerHTML
. Workaround: use <pre>
for code with
20 | newlines.
21 |
22 |
23 | Change Log
24 | 29 March 2007
25 |
26 | Added tests for PHP support
27 | to address
28 | issue 3 .
30 | Fixed
31 | bug : prettyPrintOne
was not halting. This was not
33 | reachable through the normal entry point.
34 | Fixed
35 | bug : recursing into a script block or PHP tag that was not properly
37 | closed would not silently drop the content.
38 | (test )
39 | Fixed
40 | bug : was eating tabs
42 | (test )
43 | Fixed entity handling so that the caveat
44 |
45 | Caveats: please properly escape less-thans. x<y
46 | instead of x<y , and use " instead of
47 | " for string delimiters.
48 |
49 | is no longer applicable.
50 | Added noisefree's C#
51 | patch
53 | Added a distribution that has comments and
54 | whitespace removed to reduce download size from 45.5kB to 12.8kB.
55 |
56 | 4 Jul 2008
57 |
58 | Added language specific formatters that are triggered by the presence
59 | of a lang-<language-file-extension>
60 | Fixed bug : python handling of '''string'''
61 | Fixed bug: /
in regex [charsets] should not end regex
62 |
63 | 5 Jul 2008
64 |
65 | Defined language extensions for Lisp and Lua
66 |
67 | 14 Jul 2008
68 |
69 | Language handlers for F#, OCAML, SQL
70 | Support for nocode
spans to allow embedding of line
71 | numbers and code annotations which should not be styled or otherwise
72 | affect the tokenization of prettified code.
73 | See the issue 22
74 | testcase .
75 |
76 | 6 Jan 2009
77 |
78 | Language handlers for Visual Basic, Haskell, CSS, and WikiText
79 | Added .mxml extension to the markup style handler for
80 | Flex MXML files . See
81 | issue 37 .
84 | Added .m extension to the C style handler so that Objective
85 | C source files properly highlight. See
86 | issue 58 .
89 | Changed HTML lexer to use the same embedded source mechanism as the
90 | wiki language handler, and changed to use the registered
91 | CSS handler for STYLE element content.
92 |
93 | 21 May 2009
94 |
95 | Rewrote to improve performance on large files.
96 | See benchmarks .
97 | Fixed bugs with highlighting of Haskell line comments, Lisp
98 | number literals, Lua strings, C preprocessor directives,
99 | newlines in Wiki code on Windows, and newlines in IE6.
100 |
101 | 14 August 2009
102 |
103 | Fixed prettifying of <code>
blocks with embedded newlines.
104 |
105 | 3 October 2009
106 |
107 | Fixed prettifying of XML/HTML tags that contain uppercase letters.
108 |
109 | 19 July 2010
110 |
111 | Added support for line numbers. Bug
112 | 22
114 | Added YAML support. Bug
115 | 123
117 | Added VHDL support courtesy Le Poussin.
118 | IE performance improvements. Bug
119 | 102 courtesy jacobly.
121 | A variety of markup formatting fixes courtesy smain and thezbyg.
122 | Fixed copy and paste in IE[678].
123 | Changed output to use  
instead of
124 |
so that the output works when embedded in XML.
125 | Bug
126 | 108 .
128 |
129 |
130 |
131 |
--------------------------------------------------------------------------------
/docs/assets/vendor/prettify/README.html:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 | Javascript code prettifier
7 |
8 |
9 |
10 |
11 |
12 |
16 |
17 |
18 |
19 | Languages : CH
20 | Javascript code prettifier
21 |
22 | Setup
23 |
24 | Download a distribution
25 | Include the script and stylesheets in your document
26 | (you will need to make sure the css and js file are on your server, and
27 | adjust the paths in the script and link tag)
28 |
29 | <link href="prettify.css" type="text/css" rel="stylesheet" />
30 | <script type="text/javascript" src="prettify.js"></script>
31 | Add onload="prettyPrint()"
to your
32 | document's body tag.
33 | Modify the stylesheet to get the coloring you prefer
34 |
35 |
36 | Usage
37 | Put code snippets in
38 | <pre class="prettyprint">...</pre>
39 | or <code class="prettyprint">...</code>
40 | and it will automatically be pretty printed.
41 |
42 |
43 |
44 | The original
45 | Prettier
46 |
47 | class Voila {
49 | public:
50 | // Voila
51 | static const string VOILA = "Voila";
52 |
53 | // will not interfere with embedded tags .
54 | }
55 |
56 | class Voila {
57 | public:
58 | // Voila
59 | static const string VOILA = "Voila";
60 |
61 | // will not interfere with embedded tags .
62 | }
63 |
64 |
65 | FAQ
66 | Which languages does it work for?
67 | The comments in prettify.js are authoritative but the lexer
68 | should work on a number of languages including C and friends,
69 | Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles.
70 | It works passably on Ruby, PHP, VB, and Awk and a decent subset of Perl
71 | and Ruby, but, because of commenting conventions, doesn't work on
72 | Smalltalk, or CAML-like languages.
73 |
74 | LISPy languages are supported via an extension:
75 | lang-lisp.js
.
77 | And similarly for
78 | CSS
,
80 | Haskell
,
82 | Lua
,
84 | OCAML, SML, F#
,
86 | Visual Basic
,
88 | SQL
,
90 | Protocol Buffers
, and
92 | WikiText
..
94 |
95 |
If you'd like to add an extension for your favorite language, please
96 | look at src/lang-lisp.js and file an
97 | issue including your language extension, and a testcase.
99 |
100 | How do I specify which language my code is in?
101 | You don't need to specify the language since prettyprint()
102 | will guess. You can specify a language by specifying the language extension
103 | along with the prettyprint
class like so:
104 | <pre class="prettyprint lang-html ">
106 | The lang-* class specifies the language file extensions.
107 | File extensions supported by default include
108 | "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html",
109 | "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh",
110 | "xhtml", "xml", "xsl".
111 | </pre>
112 |
113 | It doesn't work on <obfuscated code sample> ?
114 | Yes. Prettifying obfuscated code is like putting lipstick on a pig
115 | — i.e. outside the scope of this tool.
116 |
117 | Which browsers does it work with?
118 | It's been tested with IE 6, Firefox 1.5 & 2, and Safari 2.0.4.
119 | Look at the test page to see if it
120 | works in your browser.
121 |
122 | What's changed?
123 | See the change log
124 |
125 | Why doesn't Prettyprinting of strings work on WordPress?
126 | Apparently wordpress does "smart quoting" which changes close quotes.
127 | This causes end quotes to not match up with open quotes.
128 |
This breaks prettifying as well as copying and pasting of code samples.
129 | See
130 | WordPress's help center for info on how to stop smart quoting of code
132 | snippets.
133 |
134 | How do I put line numbers in my code?
135 | You can use the linenums
class to turn on line
136 | numbering. If your code doesn't start at line number 1, you can
137 | add a colon and a line number to the end of that class as in
138 | linenums:52
.
139 |
140 |
For example
141 |
<pre class="prettyprint linenums:4 "
142 | >// This is line 4.
143 | foo();
144 | bar();
145 | baz();
146 | boo();
147 | far();
148 | faz();
149 | <pre>
150 | produces
151 | // This is line 4.
153 | foo();
154 | bar();
155 | baz();
156 | boo();
157 | far();
158 | faz();
159 |
160 |
161 | How do I prevent a portion of markup from being marked as code?
162 | You can use the nocode
class to identify a span of markup
163 | that is not code.
164 |
<pre class=prettyprint>
165 | int x = foo(); /* This is a comment <span class="nocode">This is not code</span>
166 | Continuation of comment */
167 | int y = bar();
168 | </pre>
169 | produces
170 |
171 | int x = foo(); /* This is a comment This is not code
172 | Continuation of comment */
173 | int y = bar();
174 |
175 |
176 | For a more complete example see the issue22
177 | testcase .
178 |
179 | I get an error message "a is not a function" or "opt_whenDone is not a function"
180 | If you are calling prettyPrint
via an event handler, wrap it in a function.
181 | Instead of doing
182 |
183 | addEventListener('load', prettyPrint, false);
185 |
186 | wrap it in a closure like
187 |
188 | addEventListener('load', function (event) { prettyPrint() }, false);
190 |
191 | so that the browser does not pass an event object to prettyPrint
which
192 | will confuse it.
193 |
194 |
195 |
196 |
202 |
203 |
204 |
--------------------------------------------------------------------------------
/docs/assets/vendor/prettify/prettify-min.css:
--------------------------------------------------------------------------------
1 | .pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee}
--------------------------------------------------------------------------------
/docs/classes/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Redirector
5 |
6 |
7 |
8 | Click here to redirect
9 |
10 |
11 |
--------------------------------------------------------------------------------
/docs/files/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Redirector
5 |
6 |
7 |
8 | Click here to redirect
9 |
10 |
11 |
--------------------------------------------------------------------------------
/docs/files/src_comps_dependency.js.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | src/comps/dependency.js - yosonjs
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
25 |
26 |
27 |
28 |
58 |
59 |
60 |
61 | Show:
62 |
63 |
64 | Inherited
65 |
66 |
67 |
68 |
69 | Protected
70 |
71 |
72 |
73 |
74 | Private
75 |
76 |
77 |
78 | Deprecated
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
File: src/comps/dependency.js
88 |
89 |
90 |
91 | define([
92 | 'yoson'
93 | ], function(yOSON){
94 | /**
95 | * Class that makes a request by a url and indicates if its ready or not
96 | * @class Dependency
97 | * @constructor
98 | * @param {String} url Sets the url to request
99 | * @example
100 | * var url = "http://misite.com/mylib.js";
101 | * //create and object setting the url to call
102 | * var objDependency = new yOSON.Dependency(url);
103 | * //request the url
104 | * objDependency.request({
105 | * onRequest: function(){
106 | * //when request
107 | * },
108 | * onReady: function(){
109 | * //when ready
110 | * },
111 | * onError: function(){
112 | * //when error occurs
113 | * },
114 | * });
115 | */
116 | var Dependency = function(url){
117 | this.url = url;
118 | this.status = "request";
119 | this.message = "";
120 | this.events = {};
121 | };
122 | /**
123 | * Returns the status of the request
124 | * @method getStatus
125 | * @return {String} status of the request "request" | "ready" | "error"
126 | */
127 | Dependency.prototype.getStatus = function(){
128 | return this.status;
129 | };
130 | /**
131 | * Calls the request of the script
132 | * @method request
133 | * @param {Object} events Settings the callbacks
134 | */
135 | Dependency.prototype.request = function(events){
136 | var that = this;
137 |
138 | if(typeof events !== "undefined"){
139 | that.events = events;
140 | }
141 |
142 | that.onRequest();
143 | var newScript = that.createNewScript(that.url);
144 | that.requestIE(newScript, function(){
145 | newScript.onload = function(){
146 | that.onReadyRequest(this);
147 | };
148 | newScript.onerror = function(){
149 | that.onErrorRequest();
150 | };
151 | });
152 | document.getElementsByTagName("head")[0].appendChild(newScript);
153 | };
154 |
155 | Dependency.prototype.createNewScript = function(urlSource){
156 | var script = document.createElement("script");
157 | script.type = "text/javascript";
158 | script.src = urlSource;
159 | return script;
160 | };
161 |
162 | /**
163 | * Triggers when the request has started
164 | * @method onRequest
165 | */
166 | Dependency.prototype.onRequest = function(){
167 | this.requestCallBackEvent('onRequest');
168 | };
169 |
170 | /**
171 | * Triggers when the request is successful
172 | * @method onReadyRequest
173 | */
174 | Dependency.prototype.onReadyRequest = function(instanceLoaded){
175 | this.status = "ready";
176 | this.requestCallBackEvent('onReady', instanceLoaded);
177 | };
178 | /**
179 | * Triggers when the request has an error when loading the script
180 | * @method onErrorRequest
181 | */
182 | Dependency.prototype.onErrorRequest = function(){
183 | this.status = "error";
184 | this.requestCallBackEvent('onError');
185 | };
186 |
187 | Dependency.prototype.requestCallBackEvent = function(){
188 | var arrayOfArguments = [].slice.call(arguments, 0);
189 | var eventName = arrayOfArguments[0];
190 | var eventSelf = this.events[eventName];
191 | var paramsToPass = [];
192 | if(arrayOfArguments.length > 1){
193 | paramsToPass = arrayOfArguments.slice(1);
194 | }
195 | if(typeof eventSelf === "function"){
196 | eventSelf.apply(this, paramsToPass);
197 | }
198 | };
199 | /**
200 | * Calls the request of the script for IE browser
201 | * @method requestIE
202 | * @param {Object} src the newScript created in the method request
203 | * @param {Object} events Sets the callbacks
204 | */
205 | Dependency.prototype.requestIE = function(scriptElement, onNoIEBrowser){
206 | var that = this;
207 | if(scriptElement.readyState){
208 | scriptElement.onreadystatechange = function(){
209 | if(scriptElement.readyState=="loaded" || scriptElement.readyState=="complete"){
210 | scriptElement.onreadystatechange=null;
211 | that.onReadyRequest();
212 | }
213 | };
214 | } else {
215 | onNoIEBrowser.call(that);
216 | }
217 | };
218 |
219 | yOSON.Components.Dependency = Dependency;
220 | return Dependency;
221 | });
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
--------------------------------------------------------------------------------
/docs/files/src_managers_dependency.js.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | src/managers/dependency.js - yosonjs
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
25 |
26 |
27 |
28 |
58 |
59 |
60 |
61 | Show:
62 |
63 |
64 | Inherited
65 |
66 |
67 |
68 |
69 | Protected
70 |
71 |
72 |
73 |
74 | Private
75 |
76 |
77 |
78 | Deprecated
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
File: src/managers/dependency.js
88 |
89 |
90 |
91 | define([
92 | "yoson",
93 | "../../src/comps/single-promise.js",
94 | "../../src/comps/dependency.js"
95 | ], function(yOSON, SinglePromise, Dependency){
96 | /**
97 | * Class manager for one or more requests
98 | * @class DependencyManager
99 | * @requires Dependency
100 | * @constructor
101 | * @example
102 | * // create and object setting the class
103 | * var objDependencyManager = new yOSON.DependencyManager();
104 | * // example of setting the static host
105 | * objdependencymanager.setStaticHost("http://static.host/");
106 | * // example of setting the static host
107 | * objdependencymanager.setVersionUrl("?v=0.1");
108 | * // request the url
109 | * objDependency.ready(['url1'], function(){
110 | * // execute here when ready
111 | * });
112 | */
113 | var DependencyManager = function(){
114 | this.data = {};
115 | this.loaded = {};
116 |
117 | this.config = {
118 | staticHost: yOSON.statHost || "",
119 | versionUrl: yOSON.statVers || ""
120 | };
121 | };
122 |
123 | /**
124 | * Sets the host of static elements
125 | * @method setStaticHost
126 | * @param {String} hostName the host of the static elements,
127 | * like a CDN url
128 | * @example
129 | * objDependencyManager.setStaticHost("http://cdnjs.com");
130 | */
131 | DependencyManager.prototype.setStaticHost = function(hostName){
132 | this.config.staticHost = hostName;
133 | };
134 |
135 | /**
136 | * Gets saved host
137 | * @method getStaticHost
138 | * @return {String} Get the saved host with the method setStaticHost
139 | * @example
140 | * //returns "http://cdnjs.com" if set
141 | * objDependencyManager.getStaticHost();
142 | */
143 | DependencyManager.prototype.getStaticHost = function(){
144 | return this.config.staticHost;
145 | };
146 |
147 | /**
148 | * Sets the suffix for the url, ideally when working with versioned elements
149 | * @method setVersionUrl
150 | * @param {String} versionNumber the suffix or number for concatenating in the url
151 | * @example
152 | * objDependencyManager.setVersionUrl("?v=0.1");
153 | */
154 | DependencyManager.prototype.setVersionUrl = function(versionNumber){
155 | this.config.versionUrl = versionNumber;
156 | };
157 |
158 | /**
159 | * Get saved suffix
160 | * @method getVersionUrl
161 | * @return {String} Get saved suffix with the setVersionUrl method
162 | * @example
163 | * //if setting "?v=0.1" return that
164 | * objDependencyManager.getVersionUrl();
165 | */
166 | DependencyManager.prototype.getVersionUrl = function(){
167 | var result = "";
168 | if(this.config.versionUrl !== ""){
169 | result = this.config.versionUrl;
170 | }
171 | return result;
172 | };
173 |
174 | /**
175 | * Transforms the url to a request
176 | * @method transformUrl
177 | * @param {String} url the url itself to be transformed and ready for request
178 | * @return {String} the url transformed
179 | */
180 | DependencyManager.prototype.transformUrl = function(url){
181 | var urlResult = "",
182 | regularExpresion = /^(http:\/\/|https:\/\/|\/\/)?(www)?([\w-]+\.\w+)+(\/[\w-]+)+\.\w+/g;
183 | if(regularExpresion.test(url)){
184 | urlResult = url;
185 | } else {
186 | urlResult = this.sanitizeDoubleSlashes( this.config.staticHost + url + this.getVersionUrl() );
187 | }
188 | return urlResult;
189 | };
190 |
191 | /**
192 | * Sanitize double slashes in url
193 | * @method SanitizeDoubleslashes
194 | * @param {String} url the url self to sanitize
195 | * @return {String} the url cleaned
196 | */
197 | DependencyManager.prototype.sanitizeDoubleSlashes = function(url){
198 | var regularExpression = /([^\/:])\/+([^\/])/g;
199 | return url.replace(regularExpression, "$1/$2");
200 | };
201 |
202 | /**
203 | * Generates the id for the manager from the url
204 | * @method generateId
205 | * @param {String} url the url self to generate your id
206 | */
207 | DependencyManager.prototype.generateId = function(url){
208 | return (url.indexOf('//')!=-1)?url.split('//')[1].split('?')[0].replace(/[/.:]/g,'_'):url.split('?')[0].replace(/[/.:]/g,'_');
209 | };
210 |
211 | /**
212 | * Receives a url from the manager
213 | * @method addScript
214 | * @param {String} url the url self to request in the manager
215 | */
216 | DependencyManager.prototype.addScript = function(url){
217 | var id = this.generateId( url );
218 | var promiseEntity = new SinglePromise();
219 | if(this.alreadyInCollection(id)){
220 | return this.data[id].promiseEntity;
221 | //return 'the dependence is already appended';
222 | } else {
223 | this.data[id] = new Dependency(url);
224 | // Hago la consulta del script
225 | this.data[id].request({
226 | onReady: function(){
227 | promiseEntity.done();
228 | },
229 | onError: function(){
230 | promiseEntity.fail();
231 | }
232 | });
233 | this.data[id].promiseEntity = promiseEntity;
234 | }
235 | return promiseEntity;
236 | };
237 |
238 | /**
239 | * method that receives a list of urls to be requested and callbacks when the requests are ready
240 | * @method ready
241 | * @param {Array} urlList List of urls to request
242 | * @param {Function} onReady Callback to execute when the all requests are ready
243 | */
244 | DependencyManager.prototype.ready = function(urlList, onReady, onError){
245 | var index = 0,
246 | that = this;
247 | var queueQuering = function(list){
248 | if(index < list.length){
249 | var urlToQuery = that.transformUrl(list[index]);
250 | that.addScript(urlToQuery).then(function(){
251 | index++;
252 | queueQuering(urlList);
253 | }, onError);
254 | } else {
255 | onReady.apply(that);
256 | }
257 | };
258 | queueQuering(urlList);
259 | };
260 |
261 | /**
262 | * Returns saved dependency in the manager
263 | * @method getDependency
264 | * @param {String} url the url to get in the manager
265 | * @return {Object} the object Dependency created by the url
266 | */
267 | DependencyManager.prototype.getDependency = function(url){
268 | var id = this.generateId(url);
269 | return this.data[id];
270 | };
271 |
272 | /**
273 | * Queries if its appended in the collection of the manager
274 | * @method alreadyInCollection
275 | * @param {String} id the id generated by the url
276 | * @return {Object} the object Dependency created by the url
277 | */
278 | DependencyManager.prototype.alreadyInCollection = function(id){
279 | return this.data[id];
280 | };
281 |
282 | /**
283 | * Queries if the dependency is loaded in the manager
284 | * @method alreadyLoaded
285 | * @param {String} id the id generated by the url
286 | * @return {Object} the object Dependency created by the url
287 | */
288 | DependencyManager.prototype.alreadyLoaded = function(id){
289 | return ( typeof this.loaded[id] !== "undefined");
290 | };
291 |
292 | yOSON.Components.DependencyManager = DependencyManager;
293 | return DependencyManager;
294 | });
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | yosonjs
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
25 |
26 |
27 |
28 |
58 |
59 |
60 |
61 | Show:
62 |
63 |
64 | Inherited
65 |
66 |
67 |
68 |
69 | Protected
70 |
71 |
72 |
73 |
74 | Private
75 |
76 |
77 |
78 | Deprecated
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | Browse to a module or class using the sidebar to view its API documentation.
91 |
92 |
93 |
Keyboard Shortcuts
94 |
95 |
96 | Press s to focus the API search box.
97 |
98 | Use Up and Down to select classes, modules, and search results.
99 |
100 | With the API search box or sidebar focused, use ⌘ -Left or ⌘ -Right to switch sidebar tabs.
101 |
102 | With the API search box or sidebar focused, use Ctrl+Left and Ctrl+Right to switch sidebar tabs.
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/docs/modules/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Redirector
5 |
6 |
7 |
8 | Click here to redirect
9 |
10 |
11 |
--------------------------------------------------------------------------------
/examples/boilerplate/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Boilerplate in yOSONJS
6 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/examples/boilerplate/js/loader.js:
--------------------------------------------------------------------------------
1 | var objLoader = new yOSON.Components.Loader(schema);
2 | objLoader.init(yOSON.module, yOSON.controller, yOSON.action);
3 |
--------------------------------------------------------------------------------
/examples/boilerplate/js/modules.js:
--------------------------------------------------------------------------------
1 | /**
2 | Hello, this is the example of declare a module in yOSON
3 | @main my-first-module
4 | @author @frontend-labs
5 | */
6 | yOSON.AppCore.addModule("my-first-module", function(){
7 | var welcome = function(){
8 | document.body.innerHTML = "Welcome to yOSON";
9 | };
10 | return {
11 | init: function(){
12 | welcome();
13 | }
14 | }
15 | });
16 |
17 |
--------------------------------------------------------------------------------
/examples/boilerplate/js/schema.js:
--------------------------------------------------------------------------------
1 | var schema = {
2 | 'modules':{
3 | 'allModules': function(){
4 | //alert("sector donde corre sin importar el nombre del modulo");
5 | },
6 | 'default':{
7 | 'allControllers': function(){
8 | //alert("sector donde corre sin importar el nombre del controller en el modulo usuario");
9 | },
10 | 'controllers':{
11 | 'index': {
12 | 'allActions':function(){
13 | },
14 | 'actions':{
15 | 'index': function(){
16 | yOSON.AppCore.runModule("my-first-module");
17 | },
18 | 'byDefault':function(){
19 | //alert("si no existe un action, este action corre por defecto");
20 | }
21 | }
22 | },
23 | 'byDefault': function(){
24 | //alert("si no existe un controller debería ser por default este controller");
25 | }
26 | }
27 | },
28 | 'byDefault': function(){
29 | //alert('corriendo modulo por defecto');
30 | }
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/examples/debug-area/css/style.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/examples/debug-area/css/style.css
--------------------------------------------------------------------------------
/examples/debug-area/demo-loader.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug simple loader Schema
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/dependences-handler-error.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug dependences
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/dependences.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug dependences
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/js/data/rulesValidate.js:
--------------------------------------------------------------------------------
1 | var dataRules = {
2 | '#experienceF' : {
3 | '_otra_empresa' : {require : true},
4 | '_otro_rubro' : {type : 'all'},
5 | '_id_puesto' : {require : true},
6 | '_otro_puesto' : {require : true},
7 | '_id_nivel_puesto' : {require : true},
8 | '_otro_nivel_puesto' : {require : true},
9 | '_id_area' : {require : true},
10 | '_id_tipo_proyecto' : {require : true},
11 | '_nombre_proyecto' : {require : true},
12 | '_costo_proyecto' : {type : 'decimal'},
13 | '_inicio_mes' : {require : true},
14 | '_inicio_ano' : {require : true},
15 | '_fin_mes' : {require : true},
16 | '_fin_ano' : {require : true},
17 | '_comentarios' : {type : 'all'}
18 | },
19 | '#studyF' : {
20 | '_id_nivel_estudio' : {require : true},
21 | '_id_nivel_estudio_tipo' : {require : true},
22 | '_otro_estudio' : {require : true},
23 | '_colegiatura_numero' : {type : 'number'},
24 | '_institucion' : {require : true},
25 | '_pais_estudio' : {require : true},
26 | '_id_tipo_carrera' : {require : true},
27 | '_id_carrera' : {require : true},
28 | '_otro_carrera' : {require : true},
29 | '_otra_carrera' : {require : true},
30 | '_inicio_mes' : {require : true},
31 | '_inicio_ano' : {require : true},
32 | '_fin_mes' : {require : true},
33 | '_fin_ano' : {require : true}
34 | },
35 | '#studyOtherF' : {
36 | '_id_nivel_estudio_tipo' : {require : true},
37 | '_otro_estudio' : {require : true},
38 | '_otra_carrera' : {require : true},
39 | '_institucion' : {require : true},
40 | '_pais_estudio' : {require : true},
41 | '_inicio_mes' : {require : true},
42 | '_inicio_ano' : {require : true},
43 | '_fin_mes' : {require : true},
44 | '_fin_ano' : {require : true}
45 | },
46 | '#languagesF' : {
47 | '_id_idioma' : {require : true},
48 | '_nivel_idioma' : {require : true}
49 | },
50 | '#programsF' : {
51 | '_id_programa_computo' : {require : true},
52 | '_nivel' : {require : true}
53 | },
54 | '#referenceF' : {
55 | '_listaexperiencia' : {require : true},
56 | '_nombre' : {require : true},
57 | '_cargo' : {require : true},
58 | '_telefono' : {require : true, type: 'phone'},
59 | '_telefono2' : {type: 'phone'},
60 | '_email' : {type : 'email'}
61 | },
62 | '#preguntasF' : {
63 | '_pregunta' : {require : true}
64 | },
65 | '#frmContacSelection' : {
66 | 'txtCompany' : {require : true},
67 | 'txtPhoneCompany' : {require : true, type: 'phone'},
68 | 'txtPhone' : {require : true, type: 'phone'},
69 | 'txtContact' : {require : true},
70 | 'txtEmail' : {require : true, type : 'email'},
71 | 'txaMessage' : {require : true}
72 | },
73 | '#frmSendEmail' : {
74 | 'nombreEmisor' : {require : true},
75 | 'nombreReceptor' : {require : true},
76 | 'correoEmisor' : {require : true, type : 'email'},
77 | 'correoReceptor' : {require : true, type : 'email'}
78 | }
79 | };
80 |
--------------------------------------------------------------------------------
/examples/debug-area/js/demo-loader.js:
--------------------------------------------------------------------------------
1 | var schema = {
2 | 'modules':{
3 | 'allModules': function(){
4 | //alert("sector donde corre sin importar el nombre del modulo");
5 | },
6 | 'usuario':{
7 | 'allControllers': function(){
8 | //alert("sector donde corre sin importar el nombre del controller en el modulo usuario");
9 | },
10 | 'controllers':{
11 | 'aviso': {
12 | 'allActions':function(){
13 | //alert("corre sin importar si hay actions o no");
14 | },
15 | 'actions':{
16 | 'dashboard': function(){
17 | alert('corriendo action dashboard del controller aviso');
18 | },
19 | 'byDefault':function(){
20 | //alert("si no existe un action, este action corre por defecto");
21 | }
22 | }
23 | },
24 | 'byDefault': function(){
25 | //alert("si no existe un controller debería ser por default este controller");
26 | }
27 | }
28 | },
29 | 'byDefault': function(){
30 | //alert('corriendo modulo por defecto');
31 | }
32 | }
33 | };
34 | var objLoader = new yOSON.Components.Loader(schema);
35 | //
36 | var querys = {
37 | "nothing":"",
38 | "onlyModule":"usuario",
39 | "moduleWithController":{
40 | "module": "usuario",
41 | "controller": "aviso"
42 | },
43 | "moduleControllerAction":{
44 | "module": "usuario",
45 | "controller": "aviso",
46 | "action": "dashboard"
47 | }
48 | }
49 | //querys.nothing
50 | var query = querys.nothing;
51 | objLoader.init(querys.nothing);
52 | //querys.onlymodule
53 | alert("querys.onlyModule");
54 | query = querys.onlyModule;
55 | objLoader.init(query);
56 | alert("modulewithcontroller");
57 | query = querys.moduleWithController;
58 | objLoader.init(query.module, query.controller);
59 | //querys.modulewithcontrollerAction
60 | alert("moduleControllerAction");
61 | query = querys.moduleControllerAction;
62 | objLoader.init(query.module, query.controller, query.action);
63 |
--------------------------------------------------------------------------------
/examples/debug-area/js/dependences.js:
--------------------------------------------------------------------------------
1 | var objDependency = new yOSON.Components.Dependency('http://code.jquery.com/jquery-1.11.0.min.js');
2 | objDependency.request({
3 | onReady:function(instanceLoaded){
4 | console.log('instanceLoaded', instanceLoaded);
5 | }
6 | });
7 |
--------------------------------------------------------------------------------
/examples/debug-area/js/manager-dependences-handler-error.js:
--------------------------------------------------------------------------------
1 | //define the modules
2 | //var dependencyManager = new yOSON.DependencyManager();
3 | var dependencyManager = new yOSON.Components.DependencyManager();
4 | //append the demo urls
5 | var dependences = [
6 | 'http://code.jquery.com/jquery-1.11.0.min.js',
7 | 'http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js',
8 | 'http://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js'
9 | ];
10 |
11 | var dependencesWithFake = [
12 | 'http://code.jquery.com/jquery-1.11.0.min.js',
13 | 'http://demououou.com/demoOOOOOOOO.js'
14 | ];
15 | //when is ready
16 | dependencyManager.ready([dependences[0]], function(){
17 | console.log('done!', $);
18 | });
19 |
20 | //when error
21 | dependencyManager.ready(dependencesWithFake, function(){
22 | console.log('bla bla bla');
23 | }, function(){
24 | console.log('no pudo ejecutarse el "bla, bla, bla"');
25 | });
26 |
27 | dependencyManager.ready([ dependences[0], dependences[1] ], function(){
28 | console.log('se debe ejecutar desde la cache del manager!', $.ui);
29 | });
30 |
31 |
--------------------------------------------------------------------------------
/examples/debug-area/js/manager-dependences.js:
--------------------------------------------------------------------------------
1 | //define the modules
2 | var dependencyManager = new yOSON.Components.DependencyManager();
3 | dependencyManager.setStaticHost("http://cdn.aptixtus.e3.pxe/js/");
4 | //append the demo urls
5 | var dependences = [
6 | 'http://code.jquery.com/jquery-1.11.0.min.js',
7 | 'http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'
8 | //'http://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js'
9 | ];
10 |
11 | var dependencesApt = [
12 | 'src/libs/yoson/data/rulesValidate.js',
13 | 'src/libs/underscore.js',
14 | 'src/libs/jquery/jqFancybox.js'
15 | ];
16 |
17 | var empty = [];
18 | //when is ready
19 | dependencyManager.ready([], function(){
20 | console.log('mod 01');
21 | });
22 |
23 | dependencyManager.ready([dependencesApt[2]], function(){
24 | console.log('mod 02');
25 | });
26 |
27 | dependencyManager.ready([dependencesApt[2]], function(){
28 | console.log('mod 03');
29 | });
30 |
31 | dependencyManager.ready([dependencesApt[2]], function(){
32 | console.log('mod 04');
33 | });
34 |
35 | dependencyManager.ready([], function(){
36 | console.log('mod 05');
37 | });
38 |
39 | dependencyManager.ready([], function(){
40 | console.log('mod 06');
41 | });
42 |
43 | dependencyManager.ready(dependencesApt, function(){
44 | console.log('done!');
45 | });
46 |
47 | dependencyManager.ready([dependencesApt[1]], function(){
48 | console.log('mod 1');
49 | });
50 |
51 | dependencyManager.ready([], function(){
52 | console.log('mod 2');
53 | });
54 |
55 | dependencyManager.ready([dependencesApt[2]], function(){
56 | console.log('mod 3');
57 | });
58 |
59 |
--------------------------------------------------------------------------------
/examples/debug-area/js/modular-manager.js:
--------------------------------------------------------------------------------
1 | //Using the modular manager component
2 | var objModularManager = new yOSON.Components.ModularManager();
3 |
4 | objModularManager.addModule("moduleA", function(){
5 | var init = function(){
6 | console.log("hellooooooooooooo I'm in the module manager comp!!");
7 | };
8 | return {
9 | init: init
10 | }
11 | });
12 | objModularManager.runModule("moduleA");
13 |
--------------------------------------------------------------------------------
/examples/debug-area/js/modular.js:
--------------------------------------------------------------------------------
1 | var Modular = yOSON.Components.Modular;
2 | //===========
3 | var objModularA = new Modular();
4 | //create a module
5 | objModularA.create(function(){
6 | var init = function(){
7 | console.log("hello I'm moduleA!!");
8 | };
9 | return {
10 | init: init
11 | }
12 | });
13 |
14 | var objModularB = new Modular({
15 | methodInside: "ey!"
16 | });
17 |
18 | objModularB.create(function(Sb){
19 | var init = function(){
20 | console.log("hello I'm moduleB!!", Sb.methodInside);
21 | };
22 | return {
23 | init: init
24 | }
25 | });
26 |
27 | var objDontValidate = new Modular();
28 | objDontValidate.create(function(){
29 | return {
30 | init: function(){
31 | log(tmp);
32 | }
33 | }
34 | });
35 |
36 | var moduleWithPosibleError = new Modular({}, {
37 | onError: function(ex, functionName){
38 | console.log("custom error :D", functionName, ":()", ex);
39 | }
40 | });
41 |
42 | moduleWithPosibleError.create(function(){
43 | return {
44 | init: function(){
45 | log(tmp);
46 | }
47 | }
48 | });
49 |
50 | objModularA.start();
51 | objModularB.start();
52 | moduleWithPosibleError.start();
53 |
--------------------------------------------------------------------------------
/examples/debug-area/js/modules/mini-validate.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/examples/debug-area/js/modules/mini-validate.js
--------------------------------------------------------------------------------
/examples/debug-area/js/promise.js:
--------------------------------------------------------------------------------
1 | var methodTest = function(){
2 | console.log('start methodTest');
3 | var objPromise = new yOSON.Components.SinglePromise();
4 | setTimeout(function() {
5 | objPromise.done();
6 | }, 1000);
7 | return objPromise;
8 | };
9 |
10 | var whenDone = function(){
11 | var objPromise = new yOSON.Components.SinglePromise();
12 | console.log('start 2nd method');
13 | setTimeout(function() {
14 | objPromise.done();
15 | }, 1000);
16 | return objPromise;
17 | };
18 |
19 | var methodTestPassingInstance = function(){
20 | console.log('start methodTestPassingInstance');
21 | var objPromise = new yOSON.Components.SinglePromise();
22 | var dummyObject = {"msge": "Hello from methodTestPassingInstance"};
23 | setTimeout(function() {
24 | objPromise.done(dummyObject);
25 | }, 1000);
26 | return objPromise;
27 | };
28 |
29 | var methodTestPassingManyInstances = function(){
30 | console.log('start methodTestPassingInstance');
31 | var objPromise = new yOSON.Components.SinglePromise();
32 | var dummyObject = {"msge": "Hello from methodTestPassingInstance"};
33 | var anotherDummyObject = {"msge": "Hello again"};
34 | setTimeout(function() {
35 | objPromise.done(dummyObject, anotherDummyObject);
36 | }, 1000);
37 | return objPromise;
38 | };
39 |
40 | methodTest().then(function(){
41 | console.log('echo 1!');
42 | }).then(whenDone).then(function(){
43 | console.log('echo 2');
44 | });
45 |
46 | methodTestPassingInstance().then(function(objectWhenDone){
47 | console.log("show message: ", objectWhenDone.msge);
48 | });
49 |
50 | methodTestPassingManyInstances().then(function(objectWhenDone, otherObject){
51 | console.log("show message: ", objectWhenDone.msge);
52 | console.log("show message from otherObject: ", otherObject.msge);
53 | });
54 |
--------------------------------------------------------------------------------
/examples/debug-area/js/pubsub.js:
--------------------------------------------------------------------------------
1 | //===========
2 | var objPubSub = new yOSON.Components.Comunicator();
3 |
4 | //define the modules
5 | yOSON.AppCore.addModule('moduleA', function(Sb){
6 | var init = function(){
7 | console.log("hello I'm moduleA!!");
8 | objPubSub.subscribe(['suscribeFnForYosonComunicator'], suscribeFnForYosonComunicator , this);
9 | Sb.events(['suscribeFn'], suscribeFn, this);
10 | },
11 | suscribeFnForYosonComunicator = function(){
12 | console.log("Hello Im a suscribeFn I travel with YosonComunicator :D");
13 | };
14 | suscribeFn = function(){
15 | console.log("Hello Im a suscribeFn from moduleA");
16 | };
17 | return {
18 | init: init
19 | }
20 | });
21 |
22 | yOSON.AppCore.addModule('moduleB', function(Sb){
23 | var init = function(){
24 | console.log("hello I'm moduleB!!");
25 | publishFn();
26 | },
27 | publishFn = function(){
28 | Sb.trigger('suscribeFn');
29 | objPubSub.publish('suscribeFnForYosonComunicator');
30 | };
31 | return {
32 | init: init
33 | }
34 | });
35 |
36 | //run the module
37 | yOSON.AppCore.runModule('moduleA');
38 | yOSON.AppCore.runModule('moduleB');
39 |
--------------------------------------------------------------------------------
/examples/debug-area/js/schema.js:
--------------------------------------------------------------------------------
1 | var schema = {
2 | 'modules':{
3 | 'allModules': function(){
4 | //alert("sector donde corre sin importar el nombre del modulo");
5 | },
6 | 'usuario':{
7 | 'allControllers': function(){
8 | //alert("sector donde corre sin importar el nombre del controller en el modulo usuario");
9 | },
10 | 'controllers':{
11 | 'aviso': {
12 | 'allActions':function(){
13 | //alert("corre sin importar si hay actions o no");
14 | },
15 | 'actions':{
16 | 'dashboard': function(){
17 | yOSON.AppCore.runModule("demoA");
18 | yOSON.AppCore.runModule("demoB");
19 | },
20 | 'byDefault':function(){
21 | //alert("si no existe un action, este action corre por defecto");
22 | }
23 | }
24 | },
25 | 'byDefault': function(){
26 | //alert("si no existe un controller debería ser por default este controller");
27 | }
28 | }
29 | },
30 | 'byDefault': function(){
31 | //alert('corriendo modulo por defecto');
32 | }
33 | }
34 | };
35 |
--------------------------------------------------------------------------------
/examples/debug-area/js/sequential.js:
--------------------------------------------------------------------------------
1 | var firstTask = function(next){
2 | setTimeout(function() {
3 | console.log('done 1st task');
4 | next();
5 | }, 1000);
6 | };
7 |
8 | var secondTask = function(next){
9 | console.log('Hello! Im the secondTask');
10 | next();
11 | };
12 |
13 | var objSequential = new yOSON.Components.Sequential();
14 | objSequential.inQueue(firstTask).inQueue(secondTask);
15 |
--------------------------------------------------------------------------------
/examples/debug-area/js/welcome.js:
--------------------------------------------------------------------------------
1 | //define the module
2 | yOSON.AppCore.addModule('helloWorld', function(){
3 | var welcome = function(){
4 | alert('Hello Im a Module in yOSON :)');
5 | };
6 | return {
7 | init: welcome
8 | }
9 | });
10 | //run the module
11 | yOSON.AppCore.runModule('helloWorld');
12 |
--------------------------------------------------------------------------------
/examples/debug-area/manager-dependences.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug dependences
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/modular-manager.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Using the ModularManager Component
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/modular.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug simple module
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/promise.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Welcome to yOSONJS
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/examples/debug-area/pubsub.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug simple module
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/debug-area/sequential.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Using the Sequential Component
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/examples/debug-area/welcome.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Welcome to yOSONJS
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/files.md:
--------------------------------------------------------------------------------
1 | Structure of yOSON directory
2 | ============================
3 |
4 | config/ -> Folder of config by enviroment (test / build)
5 | build/ -> Folder of production library (unmified & minified)
6 | test/ -> Folder of unit tests
7 | src/ -> Folder of human code of yoson comp's
8 |
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | #
3 | #Script to create a instance of development
4 | # - install required node packages
5 | # - install git hooks
6 |
7 | node= which node 2>&1
8 | if [ $? -ne 0 ]; then
9 | echo "Please install nodeJS."
10 | echo "You can be found in http://nodejs.org/"
11 | exit 1
12 | fi
13 |
14 | npm= which npm 2>&1
15 | if [ $? -ne 0 ]; then
16 | echo "Please install the NPM (Node Packaged Modules)"
17 | fi
18 |
19 | echo "Installing required npm packages..."
20 | npm install
21 |
22 | echo "Installing git hooks..."
23 | ln -sf validate-commit-msg.js .git/hooks/commit-msg
24 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "yosonjs",
3 | "description": "Lightweight library for manage modular scripts",
4 | "version": "0.0.17-alpha",
5 | "repository": {
6 | "type": "git",
7 | "url": "https://github.com/frontend-labs/yosonjs"
8 | },
9 | "devDependencies": {
10 | "bower": "~1.2.8",
11 | "grunt": "0.4.x",
12 | "grunt-bump": "0.0.16",
13 | "grunt-cli": "0.1.x",
14 | "grunt-complexity": "0.1.x",
15 | "grunt-contrib-concat": "~0.3.0",
16 | "grunt-contrib-connect": "~0.3.0",
17 | "grunt-contrib-copy": "~0.4.1",
18 | "grunt-contrib-jasmine": "~0.7.0",
19 | "grunt-contrib-jshint": "~0.6.3",
20 | "grunt-contrib-requirejs": "~0.4.0",
21 | "grunt-contrib-uglify": "~0.2.2",
22 | "grunt-contrib-watch": "~0.4.3",
23 | "grunt-contrib-yuidoc": "~0.5.x",
24 | "grunt-conventional-changelog": "^4.1.0",
25 | "grunt-coveralls": "~1.0.0",
26 | "grunt-exec": "~0.4.0",
27 | "grunt-template-jasmine-istanbul": "~0.3.0",
28 | "grunt-template-jasmine-requirejs": "0.2",
29 | "istanbul": "~0.3.2",
30 | "requirejs": "2.1.10"
31 | },
32 | "scripts": {
33 | "build": "npm install && grunt",
34 | "start": "grunt",
35 | "test": "grunt",
36 | "ci": "istanbul cover -- grunt coverage"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/comps/communicator.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson"
3 | ], function(yOSON){
4 |
5 | // This class handles the communication between modules
6 | var Communicator = function(){
7 | this.events = {};
8 | };
9 |
10 | Communicator.prototype.subscribe = function(eventNames, functionSelfEvent, instanceOrigin){
11 | var that = this;
12 | this.finderEvents(eventNames, function(){
13 | }, function(eventName){
14 | that.addEvent(eventName, functionSelfEvent, instanceOrigin);
15 | });
16 | };
17 |
18 | Communicator.prototype.publish = function(eventName, argumentsOfEvent){
19 | var that = this;
20 | this.finderEvents([eventName], function(eventNameFound, eventFound){
21 | var instanceFound = eventFound.instanceOrigin,
22 | functionFound = eventFound.functionSelf,
23 | validArguments = that.validateArguments(argumentsOfEvent);
24 | functionFound.apply(instanceFound, validArguments);
25 | }, function(){});
26 | };
27 |
28 | Communicator.prototype.validateArguments = function(argumentsToValidate){
29 | var validArguments = [];
30 | if(typeof argumentsToValidate !== "undefined"){
31 | validArguments = argumentsToValidate;
32 | }
33 | return validArguments;
34 | };
35 |
36 | Communicator.prototype.stopSubscribe = function(EventsToStop){
37 | var that = this;
38 | this.finderEvents(EventsToStop, function(eventNameFound, eventFound){
39 | that.removeEvent(eventNameFound);
40 | }, function(){});
41 | };
42 |
43 | Communicator.prototype.addEvent = function(eventName, functionOfEvent, instanceOrigin){
44 | var bodyNewEvent = {};
45 | bodyNewEvent.instanceOrigin = instanceOrigin;
46 | bodyNewEvent.functionSelf = functionOfEvent;
47 | this.events[eventName] = bodyNewEvent;
48 | return this;
49 | };
50 |
51 | Communicator.prototype.removeEvent = function(eventName){
52 | delete this.events[eventName];
53 | };
54 |
55 | Communicator.prototype.eventAlreadyRegistered = function(eventName){
56 | var response = false;
57 | if(this.getEvent(eventName)){
58 | response = true;
59 | }
60 | return response;
61 | };
62 |
63 | Communicator.prototype.getEvent = function(eventName){
64 | return this.events[eventName];
65 | };
66 |
67 | Communicator.prototype.finderEvents = function(eventNames, whichEventFound, whichEventNotFound){
68 | var that = this;
69 | for(var index = 0; index < eventNames.length;index++){
70 | that.eachFindEvent(eventNames[index], whichEventFound, whichEventNotFound);
71 | }
72 | };
73 |
74 | Communicator.prototype.eachFindEvent = function(eventName, whichEventFound, whichEventNotFound){
75 | var that = this;
76 | if(that.eventAlreadyRegistered(eventName)){
77 | var eventFound = that.getEvent(eventName);
78 | whichEventFound.call(that, eventName, eventFound);
79 | } else {
80 | whichEventNotFound.call(that, eventName);
81 | }
82 | };
83 |
84 | yOSON.Components.Communicator = Communicator;
85 | return Communicator;
86 | });
87 |
--------------------------------------------------------------------------------
/src/comps/dependency.js:
--------------------------------------------------------------------------------
1 | define([
2 | 'yoson'
3 | ], function(yOSON){
4 | /**
5 | * Class that makes a request by a url and indicates if its ready or not
6 | * @class Dependency
7 | * @constructor
8 | * @param {String} url Sets the url to request
9 | * @example
10 | * var url = "http://misite.com/mylib.js";
11 | * //create and object setting the url to call
12 | * var objDependency = new yOSON.Dependency(url);
13 | * //request the url
14 | * objDependency.request({
15 | * onRequest: function(){
16 | * //when request
17 | * },
18 | * onReady: function(){
19 | * //when ready
20 | * },
21 | * onError: function(){
22 | * //when error occurs
23 | * },
24 | * });
25 | */
26 | var Dependency = function(url){
27 | this.url = url;
28 | this.status = "request";
29 | this.message = "";
30 | this.events = {};
31 | };
32 | /**
33 | * Returns the status of the request
34 | * @method getStatus
35 | * @return {String} status of the request "request" | "ready" | "error"
36 | */
37 | Dependency.prototype.getStatus = function(){
38 | return this.status;
39 | };
40 | /**
41 | * Calls the request of the script
42 | * @method request
43 | * @param {Object} events Settings the callbacks
44 | */
45 | Dependency.prototype.request = function(events){
46 | var that = this;
47 |
48 | if(typeof events !== "undefined"){
49 | that.events = events;
50 | }
51 |
52 | that.onRequest();
53 | var newScript = that.createNewScript(that.url);
54 | that.requestIE(newScript, function(){
55 | newScript.onload = function(){
56 | that.onReadyRequest(this);
57 | };
58 | newScript.onerror = function(){
59 | that.onErrorRequest();
60 | };
61 | });
62 | document.getElementsByTagName("head")[0].appendChild(newScript);
63 | };
64 |
65 | Dependency.prototype.createNewScript = function(urlSource){
66 | var script = document.createElement("script");
67 | script.type = "text/javascript";
68 | script.src = urlSource;
69 | return script;
70 | };
71 |
72 | /**
73 | * Triggers when the request has started
74 | * @method onRequest
75 | */
76 | Dependency.prototype.onRequest = function(){
77 | this.requestCallBackEvent('onRequest');
78 | };
79 |
80 | /**
81 | * Triggers when the request is successful
82 | * @method onReadyRequest
83 | */
84 | Dependency.prototype.onReadyRequest = function(instanceLoaded){
85 | this.status = "ready";
86 | this.requestCallBackEvent('onReady', instanceLoaded);
87 | };
88 | /**
89 | * Triggers when the request has an error when loading the script
90 | * @method onErrorRequest
91 | */
92 | Dependency.prototype.onErrorRequest = function(){
93 | this.status = "error";
94 | this.requestCallBackEvent('onError');
95 | };
96 |
97 | Dependency.prototype.requestCallBackEvent = function(){
98 | var arrayOfArguments = [].slice.call(arguments, 0);
99 | var eventName = arrayOfArguments[0];
100 | var eventSelf = this.events[eventName];
101 | var paramsToPass = [];
102 | if(arrayOfArguments.length > 1){
103 | paramsToPass = arrayOfArguments.slice(1);
104 | }
105 | if(typeof eventSelf === "function"){
106 | eventSelf.apply(this, paramsToPass);
107 | }
108 | };
109 | /**
110 | * Calls the request of the script for IE browser
111 | * @method requestIE
112 | * @param {Object} src the newScript created in the method request
113 | * @param {Object} events Sets the callbacks
114 | */
115 | Dependency.prototype.requestIE = function(scriptElement, onNoIEBrowser){
116 | var that = this;
117 | if(scriptElement.readyState){
118 | scriptElement.onreadystatechange = function(){
119 | if(scriptElement.readyState=="loaded" || scriptElement.readyState=="complete"){
120 | scriptElement.onreadystatechange=null;
121 | that.onReadyRequest();
122 | }
123 | };
124 | } else {
125 | onNoIEBrowser.call(that);
126 | }
127 | };
128 |
129 | yOSON.Components.Dependency = Dependency;
130 | return Dependency;
131 | });
132 |
--------------------------------------------------------------------------------
/src/comps/loader-schema.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 | var LoaderSchema = function(schema){
3 | this.modules = schema.modules;
4 | this.modules.allModules = function(){};
5 | this.modules.byDefault = function(){};
6 |
7 | this.controllers = {
8 | byDefault: function(){
9 |
10 | }
11 | };
12 | this.actions = {
13 | byDefault: function(){
14 |
15 | }
16 | };
17 | };
18 |
19 | LoaderSchema.prototype.appendMethod = function(nodeObject, methodName, methodSelf){
20 | if(typeof nodeObject[methodName] !== "function"){
21 | nodeObject[methodName] = methodSelf;
22 | }
23 | };
24 |
25 | LoaderSchema.prototype.overrideModuleLevel = function(moduleName, moduleNode){
26 | this.appendMethod(moduleNode, 'allControllers', function(){});
27 | this.modules[moduleName] = moduleNode;
28 | this.modules = this.modules;
29 | };
30 |
31 | LoaderSchema.prototype.setControllers = function(moduleName){
32 | this.controllers = this.modules[moduleName].controllers;
33 | };
34 |
35 | LoaderSchema.prototype.overrideControllerLevel = function(controllerName, controllerNode){
36 | this.appendMethod(controllerNode, 'allActions', function(){});
37 | this.controllers[controllerName] = controllerNode;
38 | };
39 |
40 | LoaderSchema.prototype.setActions = function(controllerName){
41 | this.actions = this.controllers[controllerName].actions;
42 | };
43 |
44 | LoaderSchema.prototype.getLevel =function(levelName){
45 | return this[levelName];
46 | };
47 |
48 | LoaderSchema.prototype.getNodeByLevel =function(levelName, nodeName){
49 | return this[levelName][nodeName];
50 | };
51 |
52 | LoaderSchema.prototype.getDefaultMethodInLevel = function(levelName){
53 | this[levelName].byDefault();
54 | };
55 |
56 | return LoaderSchema;
57 | });
58 |
--------------------------------------------------------------------------------
/src/comps/loader.js:
--------------------------------------------------------------------------------
1 | // Class that handles the execution of modules depending on 3 parameters (Module, Controller, Action)
2 | define(
3 | ["yoson",
4 | "../../src/comps/loader-schema.js"],
5 | function(yOSON, LoaderSchema){
6 |
7 | var Loader = function(schema){
8 | this.objSchema = new LoaderSchema(schema);
9 | };
10 |
11 | Loader.prototype.init = function(moduleName, controllerName, actionName){
12 |
13 | var moduleNameToQuery = this.checkLevelName(moduleName);
14 | var controllerNameToQuery = this.checkLevelName(controllerName);
15 | var actionNameToQuery = this.checkLevelName(actionName);
16 | var objSchema = this.objSchema;
17 |
18 | this.runModuleLevel(moduleNameToQuery, function(moduleFound){
19 | moduleFound.allControllers();
20 | this.runControllerLevel(controllerNameToQuery, function(controllerFound){
21 | controllerFound.allActions();
22 | this.runActionLevel(actionNameToQuery, function(actionFound){
23 | actionFound();
24 | });
25 | });
26 | });
27 | };
28 |
29 | Loader.prototype.checkLevelName = function(levelName){
30 | var result = "";
31 | if(typeof levelName !== "undefined"){
32 | result = levelName;
33 | }
34 | return result;
35 | };
36 |
37 | Loader.prototype.runModuleLevel = function(moduleName, onModuleFound){
38 | var objSchema = this.objSchema;
39 | var moduleLevel = objSchema.getLevel('modules');
40 | moduleLevel.allModules();
41 |
42 | if(moduleLevel[moduleName]){
43 | var module = moduleLevel[moduleName];
44 |
45 | objSchema.overrideModuleLevel(moduleName, module);
46 | objSchema.setControllers(moduleName);
47 |
48 | onModuleFound.call(this, module);
49 | } else {
50 | objSchema.getDefaultMethodInLevel('modules');
51 | }
52 | };
53 |
54 | Loader.prototype.runControllerLevel = function(controllerName, onControllerFound){
55 | var objSchema = this.objSchema,
56 | controllerLevel = objSchema.getLevel('controllers');
57 |
58 | if(controllerLevel[controllerName]){
59 | var controller = controllerLevel[controllerName];
60 | objSchema.setActions(controllerName);
61 |
62 | onControllerFound.call(this, controller);
63 | } else {
64 | objSchema.getDefaultMethodInLevel('controllers');
65 | }
66 | };
67 |
68 | Loader.prototype.runActionLevel = function(actionName, onActionFound){
69 | var objSchema = this.objSchema,
70 | actionLevel = objSchema.getLevel('actions');
71 |
72 | if(actionLevel[actionName]){
73 | var action = actionLevel[actionName];
74 | onActionFound.call(this, action);
75 | } else {
76 | objSchema.getDefaultMethodInLevel('actions');
77 | }
78 | };
79 |
80 | yOSON.Components.Loader = Loader;
81 |
82 | return Loader;
83 | });
84 |
--------------------------------------------------------------------------------
/src/comps/modular.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson"
3 | ], function(yOSON){
4 |
5 | //Class with pattern factory with the idea of creating modules
6 | var Modular = function(entityBridge, events){
7 | this.entityBridge = entityBridge;
8 | this.moduleInstance = "";
9 | this.status = "stop";
10 | this.events = {
11 | "onError": function(ex, functionName){
12 | yOSON.Log(functionName + "(): " + ex.message);
13 | }
14 | };
15 | if(typeof events !== "undefined"){
16 | this.events = events;
17 | }
18 | };
19 |
20 | Modular.prototype.moduleCallbackEvent = function(){
21 | var arrayOfArguments = [].slice.call(arguments, 0);
22 | var eventName = arrayOfArguments[0];
23 | var eventSelf = this.events[eventName];
24 | var paramsToPass = [];
25 | if(arrayOfArguments.length > 1){
26 | paramsToPass = arrayOfArguments.slice(1);
27 | }
28 | if(typeof eventSelf === "function"){
29 | eventSelf.apply(this, paramsToPass);
30 | }
31 | };
32 |
33 | //Creates an empty context of module
34 | Modular.prototype.create = function(moduleDefinition){
35 | this.moduleDefinition = moduleDefinition;
36 | this.moduleCallbackEvent("onCreated");
37 | };
38 |
39 | //Creates a definition of module self
40 | Modular.prototype.generateModularDefinition = function(functionName, functionSelf){
41 | var that = this;
42 | if(typeof functionSelf === "function"){
43 | return function(){
44 | try {
45 | return functionSelf.apply(this, arguments);
46 | } catch( ex ){
47 | that.moduleCallbackEvent("onError", ex, functionName);
48 | }
49 | };
50 | } else {
51 | return functionSelf;
52 | }
53 | };
54 |
55 | //Starts a simple module
56 | Modular.prototype.start = function(parameters){
57 | var params = this.dealParamaterOfModule(parameters);
58 | var moduleInstance = this.moduleDefinition(this.entityBridge);
59 | for(var propertyName in moduleInstance){
60 | var method = moduleInstance[propertyName];
61 | moduleInstance[propertyName] = this.generateModularDefinition(propertyName, method);
62 | }
63 | this.moduleInstance = moduleInstance;
64 | this.moduleCallbackEvent("onRun", moduleInstance);
65 | this.runInitMethodOfModule(params);
66 | };
67 |
68 | Modular.prototype.dealParamaterOfModule = function(parametersOfModule){
69 | var newParameters = {};
70 | if(typeof parametersOfModule !== "undefined"){
71 | newParameters = parametersOfModule;
72 | }
73 | return newParameters;
74 | };
75 |
76 | Modular.prototype.runInitMethodOfModule = function(parameters){
77 | var moduleDefinition = this.moduleInstance;
78 | if(typeof moduleDefinition.init === "function"){
79 | this.setStatusModule("run");
80 | moduleDefinition.init(parameters);
81 | }
82 | };
83 |
84 | Modular.prototype.setStatusModule = function(statusName){
85 | this.status = statusName;
86 | };
87 |
88 | Modular.prototype.getStatusModule = function(){
89 | return this.status;
90 | };
91 |
92 | yOSON.Components.Modular = Modular;
93 | return Modular;
94 | });
95 |
--------------------------------------------------------------------------------
/src/comps/sequential.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson"
3 | ], function(yOSON){
4 |
5 | var Sequential = function(){
6 | this.taskInQueueToList = {};
7 | this.listTaskInQueue = [];
8 | };
9 |
10 | Sequential.prototype.generateId = function(){
11 | return this.listTaskInQueue.length;
12 | };
13 |
14 | Sequential.prototype.getTaskById = function(id){
15 | return this.taskInQueueToList[id];
16 | };
17 |
18 | Sequential.prototype.inQueue = function(methodToPassingToQueue){
19 | var that = this;
20 | var id = this.generateId();
21 | var skeletonTask = {
22 | running: false,
23 | initAlreadyCalled: false,
24 | nextTask: function(methodWhenDoneTask){
25 | skeletonTask.running = true;
26 | if(typeof methodWhenDoneTask === "function"){
27 | methodWhenDoneTask.call(this);
28 | }
29 | that.dispatchQueue();
30 | },
31 | init: function(){
32 | if(skeletonTask.initAlreadyCalled){
33 | return;
34 | }
35 | skeletonTask.initAlreadyCalled = true;
36 | methodToPassingToQueue.call(this, skeletonTask.nextTask);
37 | }
38 | };
39 | this.taskInQueueToList[id] = skeletonTask;
40 | this.listTaskInQueue.push(this.taskInQueueToList);
41 | this.dispatchQueue();
42 | return this;
43 | };
44 |
45 | Sequential.prototype.taskIsRunning = function(id){
46 | return this.taskInQueueToList[id].running;
47 | };
48 |
49 | Sequential.prototype.dispatchQueue = function(){
50 | var that = this,
51 | index = 0,
52 | loopList = function(listQueue){
53 | if(index < listQueue.length){
54 | var taskInQueue = that.getTaskById(index);
55 | if(!that.taskIsRunning(index)){
56 | taskInQueue.init();
57 | } else {
58 | index++;
59 | loopList(listQueue);
60 | }
61 | }
62 | };
63 | loopList(this.listTaskInQueue);
64 | };
65 |
66 | yOSON.Components.Sequential = Sequential;
67 | return Sequential;
68 | });
69 |
--------------------------------------------------------------------------------
/src/comps/single-promise.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson"
3 | ], function(yOSON){
4 |
5 | var SinglePromise = function(){
6 | this.callbacks = {
7 | succeededs:[],
8 | faileds:[]
9 | };
10 | this.status = "pending";
11 | };
12 |
13 | SinglePromise.prototype.eachCallBackList = function(callbackList, onEveryCallback){
14 | for(var indexCallback = 0; indexCallback < callbackList.length; indexCallback++){
15 | onEveryCallback.call(this, callbackList[indexCallback]);
16 | }
17 | };
18 |
19 | SinglePromise.prototype.done = function(){
20 | var that = this;
21 | this.status = "done";
22 | this.dataToPass = arguments;
23 | this.eachCallBackList(this.callbacks.succeededs, function(callbackRegistered){
24 | callbackRegistered.apply(this, that.dataToPass);
25 | });
26 | };
27 |
28 | //When all tasks are successful
29 | SinglePromise.prototype.then = function(whenItsDone, whenIsFailed){
30 | var callbacks = this.callbacks;
31 |
32 | var byStatus = {
33 | "pending": function(){
34 | callbacks.succeededs.push(whenItsDone);
35 | if(typeof whenIsFailed === "function"){
36 | callbacks.faileds.push(whenIsFailed);
37 | }
38 |
39 | },
40 | "done": function(){
41 | if(typeof whenItsDone === "function"){
42 | whenItsDone.call(this);
43 | }
44 | },
45 | "fail": function(){
46 | whenIsFailed.call(this);
47 | }
48 | };
49 | byStatus[this.status]();
50 | return this;
51 | };
52 |
53 | //When the promise is broken
54 | SinglePromise.prototype.fail = function(objError){
55 | this.status = "fail";
56 | this.eachCallBackList(this.callbacks.faileds, function(callbackRegistered){
57 | callbackRegistered.call(this, objError);
58 | });
59 | };
60 |
61 | yOSON.Components.SinglePromise = SinglePromise;
62 | return SinglePromise;
63 | });
64 |
--------------------------------------------------------------------------------
/src/core.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson",
3 | "managers/dependency",
4 | "managers/modular",
5 | "comps/communicator",
6 | "comps/loader",
7 | "comps/sequential"
8 | ], function(yOSON){
9 |
10 | var objModularManager = new yOSON.Components.ModularManager(),
11 | objDependencyManager = new yOSON.Components.DependencyManager(),
12 | objCommunicator = new yOSON.Components.Communicator(),
13 | objSequential = new yOSON.Components.Sequential(),
14 | dependenceByModule = {},
15 | paramsTaked = [],
16 | triggerArgs = [];
17 |
18 | yOSON.AppCore = (function(){
19 |
20 | //Sets the main methods in the bridge of a module
21 | objModularManager.addMethodToBrigde('events', function(eventNames, functionSelfEvent, instanceOrigin){
22 | objCommunicator.subscribe(eventNames, functionSelfEvent, instanceOrigin);
23 | });
24 |
25 | objModularManager.addMethodToBrigde('trigger', function(){
26 | paramsTaked = paramsTaked.slice.call(arguments, 0);
27 | var eventNameArg = paramsTaked[0];
28 | if(paramsTaked.length > 1){
29 | triggerArgs = paramsTaked.slice(1);
30 | }
31 | objCommunicator.publish(eventNameArg, triggerArgs);
32 | });
33 |
34 | //Manages dependences
35 | var setDependencesByModule = function(moduleName, dependencesOfModule){
36 | dependenceByModule[moduleName] = dependencesOfModule;
37 | },
38 | getDependencesByModule = function(moduleName){
39 | var dependencesToReturn = [];
40 | if(dependenceByModule[moduleName]){
41 | dependencesToReturn = dependenceByModule[moduleName];
42 | }
43 | return dependencesToReturn;
44 | };
45 |
46 | return {
47 | addModule: function(moduleName, moduleDefinition, dependences){
48 | setDependencesByModule(moduleName, dependences);
49 | objModularManager.listenEvent(moduleName, "onError", function(ex, functionName){
50 | yOSON.Log("The module '" + moduleName + "' has an error: " + functionName + "(): " + ex.message);
51 | });
52 | objModularManager.addModule(moduleName, moduleDefinition);
53 | },
54 | runModule: function(moduleName, optionalParameter){
55 | var module = objModularManager.getModule(moduleName);
56 | if(module){
57 | var dependencesToLoad = getDependencesByModule(moduleName);
58 | objSequential.inQueue(function(next){
59 | objDependencyManager.ready(dependencesToLoad,function(){
60 | objModularManager.runModule(moduleName, optionalParameter);
61 | next();
62 | }, function(){
63 | yOSON.Log('Error: the module ' + moduleName + ' can\'t be loaded');
64 | next();
65 | });
66 | });
67 | } else {
68 | yOSON.Log('Error: the module ' + moduleName + ' don\'t exists');
69 | }
70 | },
71 | getModuleFunctions: function(moduleName){
72 | var currentModule = objModularManager.getModule(moduleName);
73 | definition = currentModule.moduleDefinition()
74 | if(definition.init === undefined){
75 | yOSON.Log('Error: the module ' + moduleName + ' don\'t have any functions to test');
76 | return {}
77 | }
78 | return definition.tests;
79 | },
80 | setStaticHost: function(hostName){
81 | objDependencyManager.setStaticHost(hostName);
82 | },
83 | setVersionUrl: function(versionCode){
84 | objDependencyManager.setVersionUrl(versionCode);
85 | }
86 | };
87 | })();
88 |
89 | return yOSON;
90 | });
91 |
--------------------------------------------------------------------------------
/src/managers/dependency.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson",
3 | "../../src/comps/single-promise.js",
4 | "../../src/comps/dependency.js"
5 | ], function(yOSON, SinglePromise, Dependency){
6 | /**
7 | * Class manager for one or more requests
8 | * @class DependencyManager
9 | * @requires Dependency
10 | * @constructor
11 | * @example
12 | * // create and object setting the class
13 | * var objDependencyManager = new yOSON.DependencyManager();
14 | * // example of setting the static host
15 | * objdependencymanager.setStaticHost("http://static.host/");
16 | * // example of setting the static host
17 | * objdependencymanager.setVersionUrl("?v=0.1");
18 | * // request the url
19 | * objDependency.ready(['url1'], function(){
20 | * // execute here when ready
21 | * });
22 | */
23 | var DependencyManager = function(){
24 | this.data = {};
25 | this.loaded = {};
26 |
27 | this.config = {
28 | staticHost: yOSON.statHost || "",
29 | versionUrl: yOSON.statVers || ""
30 | };
31 | };
32 |
33 | /**
34 | * Sets the host of static elements
35 | * @method setStaticHost
36 | * @param {String} hostName the host of the static elements,
37 | * like a CDN url
38 | * @example
39 | * objDependencyManager.setStaticHost("http://cdnjs.com");
40 | */
41 | DependencyManager.prototype.setStaticHost = function(hostName){
42 | this.config.staticHost = hostName;
43 | };
44 |
45 | /**
46 | * Gets saved host
47 | * @method getStaticHost
48 | * @return {String} Get the saved host with the method setStaticHost
49 | * @example
50 | * //returns "http://cdnjs.com" if set
51 | * objDependencyManager.getStaticHost();
52 | */
53 | DependencyManager.prototype.getStaticHost = function(){
54 | return this.config.staticHost;
55 | };
56 |
57 | /**
58 | * Sets the suffix for the url, ideally when working with versioned elements
59 | * @method setVersionUrl
60 | * @param {String} versionNumber the suffix or number for concatenating in the url
61 | * @example
62 | * objDependencyManager.setVersionUrl("?v=0.1");
63 | */
64 | DependencyManager.prototype.setVersionUrl = function(versionNumber){
65 | this.config.versionUrl = versionNumber;
66 | };
67 |
68 | /**
69 | * Get saved suffix
70 | * @method getVersionUrl
71 | * @return {String} Get saved suffix with the setVersionUrl method
72 | * @example
73 | * //if setting "?v=0.1" return that
74 | * objDependencyManager.getVersionUrl();
75 | */
76 | DependencyManager.prototype.getVersionUrl = function(){
77 | var result = "";
78 | if(this.config.versionUrl !== ""){
79 | result = this.config.versionUrl;
80 | }
81 | return result;
82 | };
83 |
84 | /**
85 | * Transforms the url to a request
86 | * @method transformUrl
87 | * @param {String} url the url itself to be transformed and ready for request
88 | * @return {String} the url transformed
89 | */
90 | DependencyManager.prototype.transformUrl = function(url){
91 | var urlResult = "",
92 | regularExpresion = /^(http:\/\/|https:\/\/|\/\/)?(www)?([\w-]+\.\w+)+(\/[\w-]+)+\.\w+/g;
93 | if(regularExpresion.test(url)){
94 | urlResult = url;
95 | } else {
96 | urlResult = this.sanitizeDoubleSlashes( this.config.staticHost + url + this.getVersionUrl() );
97 | }
98 | return urlResult;
99 | };
100 |
101 | /**
102 | * Sanitize double slashes in url
103 | * @method SanitizeDoubleslashes
104 | * @param {String} url the url self to sanitize
105 | * @return {String} the url cleaned
106 | */
107 | DependencyManager.prototype.sanitizeDoubleSlashes = function(url){
108 | var regularExpression = /([^\/:])\/+([^\/])/g;
109 | return url.replace(regularExpression, "$1/$2");
110 | };
111 |
112 | /**
113 | * Generates the id for the manager from the url
114 | * @method generateId
115 | * @param {String} url the url self to generate your id
116 | */
117 | DependencyManager.prototype.generateId = function(url){
118 | return (url.indexOf('//')!=-1)?url.split('//')[1].split('?')[0].replace(/[/.:]/g,'_'):url.split('?')[0].replace(/[/.:]/g,'_');
119 | };
120 |
121 | /**
122 | * Receives a url from the manager
123 | * @method addScript
124 | * @param {String} url the url self to request in the manager
125 | */
126 | DependencyManager.prototype.addScript = function(url){
127 | var id = this.generateId( url );
128 | var promiseEntity = new SinglePromise();
129 | if(this.alreadyInCollection(id)){
130 | return this.data[id].promiseEntity;
131 | //return 'the dependence is already appended';
132 | } else {
133 | this.data[id] = new Dependency(url);
134 | // Hago la consulta del script
135 | this.data[id].request({
136 | onReady: function(){
137 | promiseEntity.done();
138 | },
139 | onError: function(){
140 | promiseEntity.fail();
141 | }
142 | });
143 | this.data[id].promiseEntity = promiseEntity;
144 | }
145 | return promiseEntity;
146 | };
147 |
148 | /**
149 | * method that receives a list of urls to be requested and callbacks when the requests are ready
150 | * @method ready
151 | * @param {Array} urlList List of urls to request
152 | * @param {Function} onReady Callback to execute when the all requests are ready
153 | */
154 | DependencyManager.prototype.ready = function(urlList, onReady, onError){
155 | var index = 0,
156 | that = this;
157 | var queueQuering = function(list){
158 | if(index < list.length){
159 | var urlToQuery = that.transformUrl(list[index]);
160 | that.addScript(urlToQuery).then(function(){
161 | index++;
162 | queueQuering(urlList);
163 | }, onError);
164 | } else {
165 | onReady.apply(that);
166 | }
167 | };
168 | queueQuering(urlList);
169 | };
170 |
171 | /**
172 | * Returns saved dependency in the manager
173 | * @method getDependency
174 | * @param {String} url the url to get in the manager
175 | * @return {Object} the object Dependency created by the url
176 | */
177 | DependencyManager.prototype.getDependency = function(url){
178 | var id = this.generateId(url);
179 | return this.data[id];
180 | };
181 |
182 | /**
183 | * Queries if its appended in the collection of the manager
184 | * @method alreadyInCollection
185 | * @param {String} id the id generated by the url
186 | * @return {Object} the object Dependency created by the url
187 | */
188 | DependencyManager.prototype.alreadyInCollection = function(id){
189 | return this.data[id];
190 | };
191 |
192 | /**
193 | * Queries if the dependency is loaded in the manager
194 | * @method alreadyLoaded
195 | * @param {String} id the id generated by the url
196 | * @return {Object} the object Dependency created by the url
197 | */
198 | DependencyManager.prototype.alreadyLoaded = function(id){
199 | return ( typeof this.loaded[id] !== "undefined");
200 | };
201 |
202 | yOSON.Components.DependencyManager = DependencyManager;
203 | return DependencyManager;
204 | });
205 |
--------------------------------------------------------------------------------
/src/managers/modular.js:
--------------------------------------------------------------------------------
1 | define([
2 | "yoson",
3 | "../../src/comps/modular.js"
4 | ], function(yOSON, Modular){
5 |
6 | var ModularManager = function(){
7 | this.modules = {};
8 | this.runningModules = {};
9 | this.entityBridge = {};
10 | this.alreadyAllModulesBeRunning = false;
11 | this.moduleEvents = {};
12 | };
13 |
14 | // Receives a method for the entity communicator on modules
15 | ModularManager.prototype.addMethodToBrigde = function(methodName, methodSelf){
16 | this.entityBridge[methodName] = methodSelf;
17 | };
18 |
19 | //
20 | ModularManager.prototype.listenEvent = function(moduleName, eventName, eventSelf){
21 | this.moduleEvents[moduleName] = {};
22 | this.moduleEvents[moduleName][eventName] = eventSelf;
23 | };
24 |
25 | // Adds a module
26 | ModularManager.prototype.addModule = function(moduleName, moduleDefinition){
27 | var modules = this.modules;
28 | if(!this.getModule(moduleName)){
29 | modules[moduleName] = new Modular(this.entityBridge, this.moduleEvents[moduleName]);
30 | modules[moduleName].create(moduleDefinition);
31 | }
32 | };
33 |
34 | // Returns the module from the collection of modules
35 | ModularManager.prototype.getModule = function(moduleName){
36 | return this.modules[moduleName];
37 | };
38 |
39 | // Runs the module
40 | ModularManager.prototype.runModule = function(moduleName, optionalParameters){
41 | var module = this.getModule(moduleName);
42 | if(module){
43 | module.start(optionalParameters);
44 | }
45 | };
46 |
47 | ModularManager.prototype.whenModuleHaveStatus = function(moduleName, statusName, whenHaveStatus){
48 | var module = this.getModule(moduleName);
49 | if(module.getStatusModule() === statusName){
50 | whenHaveStatus.call(this, moduleName, module);
51 | }
52 | };
53 |
54 | yOSON.Components.ModularManager = ModularManager;
55 | return ModularManager;
56 | });
57 |
--------------------------------------------------------------------------------
/src/yoson.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 |
3 | if(typeof yOSON === "undefined"){
4 | var yOSON = {};
5 | }
6 |
7 | yOSON.Components = {};
8 |
9 | yOSON.Log = function(){
10 | try{
11 | console.log.apply(console, arguments);
12 | }catch(err){
13 | try{
14 | opera.postError.apply(opera, arguments);
15 | }catch(er){
16 | alert(Array.prototype.join.call(arguments), " ");
17 | }
18 | }
19 | };
20 |
21 | if (typeof module !== 'undefined' && module.exports) {
22 | module.exports = yOSON;
23 | }
24 |
25 | return yOSON;
26 | });
27 |
--------------------------------------------------------------------------------
/tasks/generate-dist.js:
--------------------------------------------------------------------------------
1 | module.exports = function(grunt){
2 | "use strict";
3 | var glog = grunt.log.writeln,
4 | gvlog = grunt.verbose.writeln,
5 | requirejs = require("requirejs"),
6 | requirejsConfig = {
7 | name: "core",
8 | baseUrl:"src",
9 | optimize: "none",
10 | findNestedDependencies : true,
11 | skipSemiColonInsertion: true,
12 | out:"dist/yoson.js",
13 | wrap: {
14 | start: "",
15 | end:"return yOSON;})();"
16 | }
17 | },
18 | requireDefineEnd = /return (.+;)(\n|\t| )+\}\);?(\n|\t| )*$/;
19 |
20 | var convertComps = function(name, path, contents){
21 | console.log('name', name);
22 | contents = contents.replace( /define\([^{]*?{/, "").replace(requireDefineEnd, "");
23 | if(name == "yoson"){
24 | contents = contents + " (function(){";
25 | }
26 | return contents;
27 | };
28 |
29 | var taskConcatenate = function(){
30 | var taskDone = this.async();
31 | requirejsConfig.onBuildWrite = convertComps;
32 | requirejs.optimize(requirejsConfig, function(response){
33 | console.log(response);
34 | taskDone();
35 | });
36 | };
37 | //register the task
38 | grunt.registerTask("generateDist", "compile the components of yOSON",function(){
39 | taskConcatenate.call(this);
40 | });
41 | };
42 |
--------------------------------------------------------------------------------
/test/escenarios/1/images/icon-set.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/test/escenarios/1/images/icon-set.png
--------------------------------------------------------------------------------
/test/escenarios/1/js/appload.js:
--------------------------------------------------------------------------------
1 | /*
2 | *
3 | * yOSON appLoad
4 | *
5 | * Copyright(c) 2011 yOSON
6 | * Web evangelists
7 | *
8 | * MIT Licensed
9 | */
10 |
11 | var modu = yOSON.modulo;
12 | var ctrl = yOSON.controller;
13 | var acti = yOSON.action;
14 |
15 | log('==> mod:'+modu+' - ctrl:'+ctrl+' - acti:'+acti);
16 |
17 | yOSON.AppSchema.modules.allModules();
18 | if(modu==='' || !yOSON.AppSchema.modules.hasOwnProperty(modu)){
19 | yOSON.AppSchema.modules.byDefault();
20 | }
21 | else{
22 | yOSON.AppSchema.modules[ modu ].allControllers();
23 | if(ctrl==='' || !yOSON.AppSchema.modules[ modu ].controllers.hasOwnProperty(ctrl)){
24 | yOSON.AppSchema.modules[ modu ].controllers.byDefault();
25 | }else{
26 | yOSON.AppSchema.modules[ modu ].controllers[ ctrl ].allActions();
27 | if(acti==='' || !yOSON.AppSchema.modules[ modu ].controllers[ ctrl ].actions.hasOwnProperty(acti)){
28 | yOSON.AppSchema.modules[ modu ].controllers[ ctrl ].actions.byDefault();
29 | }else{
30 | yOSON.AppSchema.modules[ modu ].controllers[ ctrl ].actions[ acti ]();
31 | }
32 | }
33 | }
34 |
35 | // underscore templateSettings
36 |
--------------------------------------------------------------------------------
/test/escenarios/1/js/modules.js:
--------------------------------------------------------------------------------
1 |
2 | yOSON.AppSchema.modules = {
3 | 'postulante': {
4 | controllers: {
5 | 'mi-cuenta': {
6 | actions: {
7 | 'index': function () {
8 | yOSON.AppCore.runModule('bar_animation');
9 | },
10 | 'mis-experiencias': function () {
11 | console.log("debe llegar aqui...");
12 | yOSON.AppCore.runModule('mini_validate', {
13 | "Perfil_postulante" : { experiencia : { context: '#experienceF', btn: '#btnExperience' }}
14 | });
15 | yOSON.AppCore.runModule('skill_add', {
16 | "Perfil_postulante" : { experiencia : { context: '#experienceF', template: '#tplExperience', btn: '#btnExperience' }}
17 | });
18 | yOSON.AppCore.runModule('skill_edit', {
19 | "Perfil_postulante" : { experiencia : { context: '#experienceF' }}
20 | });
21 | yOSON.AppCore.runModule('skill_remove', {
22 | "Perfil_postulante" : { experiencia : { context: '#experienceF' }}
23 | });
24 |
25 | yOSON.AppCore.runModule('hide_skill_block',[
26 | { context: '#experienceF', chkInput: '#chkExperience' }
27 | ]);
28 | yOSON.AppCore.runModule('input_show_more', [{
29 | context: '#experienceF', inputTagName: '_lugar',
30 | option: [{name: '_tipo_proyecto'}, {name: '_nombre_proyecto'}, {name: '_costo_proyecto'}]
31 | },
32 | {
33 | context: '#experienceF', inputTagName: '_nivel_puesto',
34 | option: {'10' : [{name: '_otro_nivel_puesto'}]}
35 | },
36 | {
37 | context: '#experienceF', inputTagName: '_id_puesto',
38 | option: {'1292' : [{name: '_otro_puesto', title: 'first_title'}]}
39 | }]);
40 | yOSON.AppCore.runModule('count_character');
41 | },
42 | 'mis-estudios' : function(){
43 | yOSON.AppCore.runModule('mini_validate', {
44 | "Perfil_postulante" : { estudio : { context: '#studyF', btn: '#btnStudy' } }
45 | });
46 | yOSON.AppCore.runModule('skill_add', {
47 | "Perfil_postulante" : { estudio : { context: '#studyF', template: '#tplStudy', btn: '#btnStudy' } }
48 | });
49 | yOSON.AppCore.runModule('skill_edit', {
50 | "Perfil_postulante" : { estudio : { context: '#studyF' } }
51 | });
52 | yOSON.AppCore.runModule('skill_remove', {
53 | "Perfil_postulante" : { estudio : { context: '#studyF' } }
54 | });
55 |
56 | yOSON.AppCore.runModule('study_options');
57 | yOSON.AppCore.runModule('autocomplete_text');
58 | yOSON.AppCore.runModule('combos_depends',[
59 | { context: '#studyF', selParent: '_id_tipo_carrera', selChild: 'id_carrera',
60 | urlAjax: '/registro/filtrar-carrera/', paramAjax: 'id_tipo_carrera' },
61 | { context: '#studyF', selParent: '_id_nivel_estudio', selChild: '_id_nivel_estudio_tipo',
62 | urlAjax: '/home/filtrar-tipo-estudio/', paramAjax: 'id_nivel_estudio', jsonDefault: false, arrExceptions: [0,1,2,3] }
63 | ]);
64 |
65 | yOSON.AppCore.runModule('hide_skill_block',[
66 | { context: '#studyF', chkInput: '#chkStudy' }
67 | ]);
68 | yOSON.AppCore.runModule('input_show_more', [{
69 | context: '#studyF', inputTagName: '_id_carrera',
70 | option: {'Otros' : [{name: '_otro_carrera', title: 'first_title'}]},
71 | label : true
72 | },
73 | {
74 | context: '#studyF', inputTagName: '_id_nivel_estudio_tipo',
75 | option: {'18' : [{name: '_colegiatura_numero'}]}
76 | }]);
77 | },
78 | 'mis-otros-estudios': function () {
79 | yOSON.AppCore.runModule('mini_validate', {
80 | "Perfil_postulante" : { otroEstudio : { context: '#studyOtherF', btn: '#btnOtherStudy' } }
81 | });
82 | yOSON.AppCore.runModule('skill_add', {
83 | "Perfil_postulante" : { otroEstudio : { context: '#studyOtherF', template: '#tplStudyOther', btn: '#btnOtherStudy' } }
84 | });
85 | yOSON.AppCore.runModule('skill_edit', {
86 | "Perfil_postulante" : { otroEstudio : { context: '#studyOtherF' } }
87 | });
88 | yOSON.AppCore.runModule('skill_remove', {
89 | "Perfil_postulante" : { otroEstudio : { context: '#studyOtherF' } }
90 | });
91 | },
92 | 'mis-idiomas': function () {
93 | yOSON.AppCore.runModule('mini_validate', {
94 | "Perfil_postulante" : { idioma: { context: '#languagesF', btn: '#btnLanguage' } }
95 | });
96 | yOSON.AppCore.runModule('skill_add', {
97 | "Perfil_postulante" : { idioma: { context: '#languagesF', template: '#tplLanguage', btn: '#btnLanguage' , separate: 'nivel', validRepeat: true } }
98 | });
99 | yOSON.AppCore.runModule('skill_edit', {
100 | "Perfil_postulante" : { idioma: { context: '#languagesF', separate: 'nivel' } }
101 | });
102 | yOSON.AppCore.runModule('skill_remove', {
103 | "Perfil_postulante" : { idioma: { context: '#languagesF' } }
104 | });
105 | },
106 | 'mis-programas': function () {
107 | yOSON.AppCore.runModule('mini_validate', {
108 | "Perfil_postulante" : { programs: { context: '#programsF', btn: '#btnPrograms' } }
109 | });
110 | yOSON.AppCore.runModule('skill_add', {
111 | "Perfil_postulante" : { programs: { context: '#programsF', template: '#tplPrograms', btn: '#btnPrograms' , separate: 'nivel', validRepeat: true } }
112 | });
113 | yOSON.AppCore.runModule('skill_edit', {
114 | "Perfil_postulante" : { programs: { context: '#programsF', separate: 'nivel' } }
115 | });
116 | yOSON.AppCore.runModule('skill_remove', {
117 | "Perfil_postulante" : { programs: { context: '#programsF' } }
118 | });
119 | },
120 | 'mis-referencias': function () {
121 | yOSON.AppCore.runModule('mini_validate', {
122 | "Perfil_postulante" : { programs : { context: '#referenceF', btn: '#btnReference' } }
123 | });
124 | yOSON.AppCore.runModule('skill_add', {
125 | "Perfil_postulante" : { programs : { context: '#referenceF', template: '#tplReference', btn: '#btnReference', separate: 'es'} }
126 | });
127 | yOSON.AppCore.runModule('skill_edit', {
128 | "Perfil_postulante" : { programs : { context: '#referenceF', separate: 'es' } }
129 | });
130 | yOSON.AppCore.runModule('skill_remove', {
131 | "Perfil_postulante" : { programs : { context: '#referenceF' } }
132 | });
133 | },
134 | 'byDefault': function () {
135 | }
136 | },
137 | allActions: function () {
138 | yOSON.AppCore.runModule('update_date', [
139 | {selTag: '_inicio_ano', selDepend: '_fin_ano'},
140 | {selTag: '_inicio_mes', selDepend: '_fin_mes'}
141 | ]);
142 | yOSON.AppCore.runModule('disable_combos',[
143 | {chkName: '_en_curso', disableds: ['_fin_mes','_fin_ano']}
144 | ]);
145 | }
146 | },
147 | byDefault: function () {},
148 | allActions: function () {}
149 | },
150 | byDefault: function () {},
151 | allControllers: function () {}
152 | },
153 |
154 | byDefault: function () {},
155 |
156 | allModules: function (oMCA) {
157 | yOSON.AppCore.runModule('window_modal');
158 | yOSON.AppCore.runModule('modal_login');
159 | yOSON.AppCore.runModule('modal_register');
160 | yOSON.AppCore.runModule('forgot_password');
161 | yOSON.AppCore.runModule('placeholder_ie');
162 | yOSON.AppCore.runModule('validate_key',[
163 | { txtInput: '.number', type: 'number' },
164 | { txtInput: '.decimal', type: 'decimal' },
165 | { txtInput: '.onlytext', type: 'text' }
166 | ]);
167 | }
168 | };
169 |
--------------------------------------------------------------------------------
/test/escenarios/1/js/src/libs/jqParsley_es.js:
--------------------------------------------------------------------------------
1 | // ParsleyConfig definition if not already set
2 | window.ParsleyConfig = window.ParsleyConfig || {};
3 | window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
4 |
5 | window.ParsleyConfig.i18n.es = $.extend(window.ParsleyConfig.i18n.es || {}, {
6 | defaultMessage: "Este valor parece ser inválido.",
7 | type: {
8 | email: "Ingrese un email válido.",
9 | url: "Ingrese una URL válida.",
10 | number: "Ingrese un número válido.",
11 | integer: "Ingrese un número válido.",
12 | digits: "Ingrese solo números.",
13 | alphanum: "Ingrese un valor alfanumérico."
14 | },
15 | notblank: "Este campo no debe estar en blanco.",
16 | required: "Este campo es requerido.",
17 | pattern: "Este campo es incorrecto.",
18 | min: "Este valor no debe ser menor que %s.",
19 | max: "Este valor no debe ser mayor que %s.",
20 | range: "Este valor debe estar entre %s y %s.",
21 | minlength: "La longitud mínima es de %s caracteres.",
22 | maxlength: "La longitud máxima es de %s caracteres.",
23 | length: "La longitud de este campo debe estar entre %s y %s caracteres.",
24 | mincheck: "Debe seleccionar al menos %s opciones.",
25 | maxcheck: "Debe seleccionar %s opciones o menos.",
26 | rangecheck: "Debe seleccionar entre %s y %s opciones.",
27 | equalto: "Este valor debe ser idéntico."
28 | });
29 |
30 | // If file is loaded after Parsley main file, auto-load locale
31 | if ('undefined' !== typeof window.ParsleyValidator)
32 | window.ParsleyValidator.addCatalog('es', window.ParsleyConfig.i18n.es, true);
33 |
--------------------------------------------------------------------------------
/test/escenarios/1/js/src/libs/template.js:
--------------------------------------------------------------------------------
1 | var dataTemplate = {
2 | 'datos_usuario': {
3 | 'skill_title': '{{=order}}. {{=title1}} {{ if(title2){ }} {{=separate}} {{=title2}} {{ } }} ',
4 |
5 | 'update_title': '{{=title1}} {{ if(title2){ }} {{=separate}} {{=title2}} {{ } }}',
6 |
7 | 'modal_delete': '{{=content}}
Aceptar Cancelar '
8 | },
9 | 'all': {
10 | 'tpl_options' : '{{=data}} '
11 | },
12 | 'buscador_proyecto': {
13 | 'search_list' : '{{=nombre}} X '
14 | },
15 | 'modal' : {
16 | 'confirm' : '{{=message}}
Aceptar Cancelar
'
17 | },
18 | 'plugins' : {
19 | 'switcher_check' : ''
20 | }
21 | };
22 |
23 |
24 |
25 | //yOSON.AppSchema.modules[yOSON.modulo].controllers[yOSON.controller].actions[yOSON.action]
26 | //dataTemplate[yOSON.modulo][yOSON.controller][yOSON.action]
27 |
28 |
--------------------------------------------------------------------------------
/test/escenarios/1/js/src/libs/utils/utils.js:
--------------------------------------------------------------------------------
1 | window.log = (typeof (log) != "undefined") ? log : function () {
2 | var a = function () {
3 | return /(local\.|dev\.)/gi.test(document.domain)
4 | };
5 | if (typeof (console) != "undefined") {
6 | if (typeof (console.log.apply) != "undefined") {
7 | console.log.apply(console, arguments)
8 | } else {
9 | console.log(Array.prototype.slice.call(arguments))
10 | }
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/test/escenarios/1/js/src/libs/yoson/data/rulesValidate.js:
--------------------------------------------------------------------------------
1 | var dataRules = {
2 | '#experienceF' : {
3 | '_otra_empresa' : {require : true},
4 | '_otro_rubro' : {type : 'all'},
5 | '_id_puesto' : {require : true},
6 | '_otro_puesto' : {require : true},
7 | '_id_nivel_puesto' : {require : true},
8 | '_otro_nivel_puesto' : {require : true},
9 | '_id_area' : {require : true},
10 | '_id_tipo_proyecto' : {require : true},
11 | '_nombre_proyecto' : {require : true},
12 | '_costo_proyecto' : {type : 'decimal'},
13 | '_inicio_mes' : {require : true},
14 | '_inicio_ano' : {require : true},
15 | '_fin_mes' : {require : true},
16 | '_fin_ano' : {require : true},
17 | '_comentarios' : {type : 'all'}
18 | },
19 | '#studyF' : {
20 | '_id_nivel_estudio' : {require : true},
21 | '_id_nivel_estudio_tipo' : {require : true},
22 | '_otro_estudio' : {require : true},
23 | '_colegiatura_numero' : {type : 'number'},
24 | '_institucion' : {require : true},
25 | '_pais_estudio' : {require : true},
26 | '_id_tipo_carrera' : {require : true},
27 | '_id_carrera' : {require : true},
28 | '_otro_carrera' : {require : true},
29 | '_otra_carrera' : {require : true},
30 | '_inicio_mes' : {require : true},
31 | '_inicio_ano' : {require : true},
32 | '_fin_mes' : {require : true},
33 | '_fin_ano' : {require : true}
34 | },
35 | '#studyOtherF' : {
36 | '_id_nivel_estudio_tipo' : {require : true},
37 | '_otro_estudio' : {require : true},
38 | '_otra_carrera' : {require : true},
39 | '_institucion' : {require : true},
40 | '_pais_estudio' : {require : true},
41 | '_inicio_mes' : {require : true},
42 | '_inicio_ano' : {require : true},
43 | '_fin_mes' : {require : true},
44 | '_fin_ano' : {require : true}
45 | },
46 | '#languagesF' : {
47 | '_id_idioma' : {require : true},
48 | '_nivel_idioma' : {require : true}
49 | },
50 | '#programsF' : {
51 | '_id_programa_computo' : {require : true},
52 | '_nivel' : {require : true}
53 | },
54 | '#referenceF' : {
55 | '_listaexperiencia' : {require : true},
56 | '_nombre' : {require : true},
57 | '_cargo' : {require : true},
58 | '_telefono' : {require : true, type: 'phone'},
59 | '_telefono2' : {type: 'phone'},
60 | '_email' : {type : 'email'}
61 | },
62 | '#preguntasF' : {
63 | '_pregunta' : {require : true}
64 | },
65 | '#frmContacSelection' : {
66 | 'txtCompany' : {require : true},
67 | 'txtPhoneCompany' : {require : true, type: 'phone'},
68 | 'txtPhone' : {require : true, type: 'phone'},
69 | 'txtContact' : {require : true},
70 | 'txtEmail' : {require : true, type : 'email'},
71 | 'txaMessage' : {require : true}
72 | },
73 | '#frmSendEmail' : {
74 | 'nombreEmisor' : {require : true},
75 | 'nombreReceptor' : {require : true},
76 | 'correoEmisor' : {require : true, type : 'email'},
77 | 'correoReceptor' : {require : true, type : 'email'}
78 | }
79 | };
--------------------------------------------------------------------------------
/test/escenarios/1/js/src/libs/yoson/template/template.js:
--------------------------------------------------------------------------------
1 | var dataTemplate = {
2 | 'datos_usuario': {
3 | 'skill_title': '{{=order}}. {{=title1}} {{ if(title2){ }} {{=separate}} {{=title2}} {{ } }} ',
4 |
5 | 'update_title': '{{=title1}} {{ if(title2){ }} {{=separate}} {{=title2}} {{ } }}',
6 |
7 | 'modal_delete': '{{=content}}
Aceptar Cancelar '
8 | },
9 | 'all': {
10 | 'tpl_options' : '{{=data}} '
11 | },
12 | 'buscador_aptitus': {
13 | 'search_list' : '{{=nombre}} X '
14 | },
15 | 'modal' : {
16 | 'confirm' : '{{=message}}
Aceptar Cancelar
'
17 | },
18 | 'plugins' : {
19 | 'switcher_check' : ''
20 | }
21 | };
22 |
23 |
24 |
25 | //yOSON.AppSchema.modules[yOSON.modulo].controllers[yOSON.controller].actions[yOSON.action]
26 | //dataTemplate[yOSON.modulo][yOSON.controller][yOSON.action]
27 |
--------------------------------------------------------------------------------
/test/escenarios/2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Intencional errors in console
7 |
20 |
21 |
22 | Intencional errors in console
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/test/escenarios/2/js/handling-error.js:
--------------------------------------------------------------------------------
1 | yOSON.AppCore.addModule("moduleWithPossibleError", function(){
2 | var st = {};
3 | return {
4 | init: function(){
5 | frikiFunction();
6 | }
7 | }
8 | });
9 |
10 | yOSON.AppCore.addModule("moduleWithPossibleError2", function(){
11 | var st = {};
12 | var catchDOM = function(){
13 | document.writeln("moduleWithPossibleError2");
14 | };
15 | return {
16 | init: function(){
17 | catchDOM();
18 | }
19 | }
20 | });
21 |
22 | yOSON.AppCore.addModule("moduleWithPossibleError3", function(){
23 | var st = {};
24 | var catchDOM = function(){
25 | events.click();
26 | };
27 | var events = {
28 | click: function(){
29 | evt.fakeEvent();
30 | }
31 | }
32 | return {
33 | init: function(){
34 | catchDOM();
35 | }
36 | }
37 | });
38 |
39 | yOSON.AppCore.runModule("moduleWithPossibleError");
40 | yOSON.AppCore.runModule("moduleWithPossibleError2");
41 | yOSON.AppCore.runModule("moduleWithPossibleError3");
42 |
--------------------------------------------------------------------------------
/test/escenarios/3/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Intencional errors in console
7 |
20 |
21 |
22 | Intencional errors in console
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/test/escenarios/3/js/handling-error.js:
--------------------------------------------------------------------------------
1 | yOSON.AppCore.addModule("moduleANeedsTheHostProtocol", function(){
2 | var st = {};
3 | var frikiFunction = function(){
4 |
5 | };
6 | return {
7 | init: function(){
8 | frikiFunction();
9 | }
10 | };
11 | }, ['//cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js']);
12 |
13 | yOSON.AppCore.runModule("moduleANeedsTheHostProtocol");
14 |
--------------------------------------------------------------------------------
/test/helper/HelperDependency.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frontend-labs/yosonjs/4c530581eee2be5476de785ec4e13005dccb2f69/test/helper/HelperDependency.js
--------------------------------------------------------------------------------
/test/scripts/schema-demo.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 | var SchemaDemo = {
3 | "modules": { //list of modules
4 | //module application
5 | "application":{
6 | //list of controllers of application module
7 | "controllers":{
8 | //index controller
9 | "index":{
10 | //list of actions of index controller
11 | "actions":{
12 | //index Action
13 | "index": function(){
14 |
15 | },
16 | "action-two": function(){
17 |
18 | },
19 | //action byDefault if not exists an action in the controller runs here
20 | "byDefault": function(){
21 |
22 | }
23 | },
24 | //this action dont care what action its executing in the controller same runs
25 | "allActions": function(){
26 |
27 | }
28 | },
29 | //page-products controller
30 | "page-products":{
31 | "actions":{
32 | "index": function(){
33 |
34 | },
35 | "detail": function(){
36 |
37 | },
38 | "cart": function(){
39 |
40 | },
41 | "byDefault": function(){
42 |
43 | }
44 | },
45 | "allActions": function(){
46 |
47 | }
48 | },
49 | //if not exists an controller runs here
50 | "byDefault": function(){
51 |
52 | }
53 | },
54 | //this controller dont care what controller in the module its executing same runs
55 | "allControllers": function(){
56 |
57 | }
58 | },
59 | "user":{
60 | "controllers":{
61 | "home":{
62 | "actions":{
63 | "index": function(){
64 |
65 | },
66 | "byDefault":function(){
67 |
68 | }
69 | },
70 | "allActions": function(){
71 |
72 | }
73 | },
74 | "profile":{
75 | "actions": {
76 | "index": function(){
77 |
78 | },
79 | "byDefault": function(){
80 |
81 | }
82 | },
83 | "allActions": function(){
84 |
85 | }
86 | },
87 | "byDefault": function(){
88 |
89 | }
90 | },
91 | "allControllers": function(){
92 |
93 | }
94 | },
95 | //the default module if not exists an module runs here
96 | "byDefault": function(){
97 |
98 | },
99 | //this module dont care what module its executing same runs
100 | "allModules": function(){
101 |
102 | }
103 | }
104 | };
105 |
106 | return SchemaDemo;
107 | });
108 |
--------------------------------------------------------------------------------
/test/spec/SpecComunicator.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/communicator.js'
3 | ],
4 | function(Communicator){
5 | var objCommunicator;
6 |
7 | beforeEach(function(){
8 | objCommunicator = new Communicator();
9 | });
10 |
11 | describe('specCommunicator', function(){
12 |
13 | it('should be subscribe a method', function(){
14 | var eventName = "fakeMethod";
15 | var fakeMethodSelf = function(){};
16 | objCommunicator.subscribe([eventName], fakeMethodSelf, this);
17 |
18 | var existMethod = objCommunicator.eventAlreadyRegistered(eventName);
19 | expect(existMethod).toBeTruthy();
20 | });
21 |
22 | it('should be publish a method', function(){
23 | var eventName = "fakeMethod";
24 | var methodSpy = jasmine.createSpy("methodSpy");
25 | objCommunicator.subscribe([eventName], methodSpy, this);
26 | objCommunicator.publish(eventName);
27 | expect(methodSpy).toHaveBeenCalled();
28 | });
29 |
30 | it('should be work when passing arguments in publish', function(){
31 | var argsOfevent = [3, 5];
32 | var eventName = "fakeMethod";
33 | var methodSpy = jasmine.createSpy("methodSpy");
34 | objCommunicator.subscribe([eventName], methodSpy, this);
35 | objCommunicator.publish(eventName, argsOfevent);
36 | expect(methodSpy).toHaveBeenCalled();
37 | expect(methodSpy).toHaveBeenCalledWith(3, 5);
38 | });
39 |
40 | describe("Validate the arguments", function(){
41 | it('should be return empty array when no exists arguments', function(){
42 | expect(objCommunicator.validateArguments()).toEqual([]);
43 | });
44 |
45 | it('should be return an array of the arguments', function(){
46 | var args = ["argument1", "argument2", "argument2"];
47 | expect(objCommunicator.validateArguments(args)).toBe(args);
48 | });
49 | });
50 |
51 | it('should be stop an event subscribed', function(){
52 | var eventName = "methodToStop";
53 | var methodSpy = jasmine.createSpy("methodSpy");
54 | objCommunicator.subscribe([eventName], methodSpy, this);
55 | objCommunicator.stopSubscribe([ eventName ]);
56 | expect(objCommunicator.getEvent(eventName)).toBeUndefined();
57 | });
58 |
59 | it('should be append a new method to subscribe', function(){
60 | var eventName = "fakeMethod";
61 | var fakeMethodSelf = function(){};
62 | objCommunicator.addEvent(eventName, fakeMethodSelf, this);
63 |
64 | var existMethod = objCommunicator.eventAlreadyRegistered(eventName);
65 | expect(existMethod).toBeTruthy();
66 | });
67 |
68 | it('should be remove an event subscribed', function(){
69 | var eventName = "methodToRemove";
70 | var eventSelf = function(){};
71 | objCommunicator.subscribe([eventName], eventSelf, this);
72 | objCommunicator.removeEvent(eventName);
73 | expect(objCommunicator.getEvent(eventName)).toBeUndefined();
74 | });
75 |
76 | describe("Verify if the event already exists", function(){
77 |
78 | it("should return true if exists", function(){
79 | var eventName = "methodToRegister";
80 | var eventSelf = function(){};
81 | objCommunicator.addEvent(eventName, eventSelf, this);
82 | expect(objCommunicator.eventAlreadyRegistered(eventName)).toBeTruthy();
83 | });
84 |
85 | it("should return false if not exists", function(){
86 | var eventName = "methodUnregistered";
87 | expect(objCommunicator.eventAlreadyRegistered(eventName)).toBeFalsy();
88 | });
89 |
90 | });
91 |
92 | describe("Get the event self", function(){
93 |
94 | it("should return the function self", function(){
95 | var eventName = "methodToRegister";
96 | var eventSelf = function(){};
97 | objCommunicator.addEvent(eventName, eventSelf, this);
98 | var resultGetEvent = objCommunicator.getEvent(eventName);
99 | expect(resultGetEvent).not.toBeUndefined();
100 | });
101 |
102 | it("should return undefined if not exists", function(){
103 | var eventName = "methodToRegister";
104 | var eventSelf = function(){};
105 | var resultGetEvent = objCommunicator.getEvent(eventName);
106 | expect(resultGetEvent).toBeUndefined();
107 | });
108 |
109 | });
110 |
111 | describe("Finder of events", function(){
112 |
113 | it("should be when found an event", function(){
114 | var eventName = "methodToRegister";
115 | var eventSelf = function(){};
116 | var onFoundEvent = jasmine.createSpy("onFoundEvent");
117 | var onNotFoundEvent = jasmine.createSpy("onNotFoundEvent");
118 |
119 | objCommunicator.addEvent(eventName, eventSelf, this);
120 | objCommunicator.finderEvents([eventName], onFoundEvent, onNotFoundEvent);
121 | expect(onFoundEvent).toHaveBeenCalled();
122 | expect(onNotFoundEvent).not.toHaveBeenCalled();
123 | });
124 |
125 | it("should be when not found an event", function(){
126 | var eventName = "methodNotToRegister";
127 | var onFoundEvent = jasmine.createSpy("onFoundEvent");
128 | var onNotFoundEvent = jasmine.createSpy("onNotFoundEvent");
129 | objCommunicator.finderEvents([eventName], onFoundEvent, onNotFoundEvent);
130 | expect(onFoundEvent).not.toHaveBeenCalled();
131 | expect(onNotFoundEvent).toHaveBeenCalled();
132 | });
133 |
134 | });
135 |
136 | });
137 | });
138 |
--------------------------------------------------------------------------------
/test/spec/SpecCore.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/core.js'
3 | ],
4 | function(yOSON){
5 |
6 | describe('Core', function(){
7 | it('should be set the staticHost', function(){
8 | yOSON.AppCore.setStaticHost('http://statichost.com/');
9 | expect(true).toBeTruthy();
10 | });
11 |
12 | it('should be set the version of the url', function(){
13 | yOSON.AppCore.setVersionUrl('?v=0.0.1');
14 | expect(true).toBeTruthy();
15 | });
16 |
17 | it('should be create a module', function(){
18 | yOSON.AppCore.addModule('nombreModulo', function(){
19 | return {
20 | init: function(){
21 |
22 | }
23 | }
24 | });
25 | expect(true).toBeTruthy();
26 | });
27 |
28 | it('should be run a module', function(done){
29 | var functionMustRun = jasmine.createSpy();
30 | yOSON.AppCore.addModule('moduleA', function(){
31 | return {
32 | init: function(){
33 | functionMustRun();
34 | expect(functionMustRun).toHaveBeenCalled();
35 | done();
36 | }
37 | }
38 | });
39 | yOSON.AppCore.runModule('moduleA');
40 | });
41 |
42 | it('should get functions to test from a module', function(){
43 | var myFunctions = {};
44 | myFunctions.calculateAddition = function(a, b){
45 | return a + b;
46 | };
47 | myFunctions.calculateDifference = function(a, b){
48 | return a - b;
49 | };
50 | yOSON.AppCore.addModule('moduleD', function(){
51 | return {
52 | init: function(){},
53 | tests : myFunctions
54 | }
55 | });
56 | var result = yOSON.AppCore.getModuleFunctions('moduleD');
57 | expect(result).toBe(myFunctions);
58 | });
59 |
60 | it('should be execute method from moduleA1 to moduleB1', function(done){
61 | var functionToBridge = jasmine.createSpy();
62 | yOSON.AppCore.addModule('moduleA1', function(Sb){
63 | var privateMethodA1 = function(){
64 | functionToBridge();
65 | expect(functionToBridge).toHaveBeenCalled();
66 | done();
67 | };
68 | return {
69 | init: function(){
70 | Sb.events(['publicMethodInModuleA1'], privateMethodA1, this);
71 | }
72 | }
73 | });
74 | yOSON.AppCore.addModule('moduleB1', function(Sb){
75 | return {
76 | init: function(){
77 | Sb.trigger('publicMethodInModuleA1');
78 | }
79 | }
80 | });
81 | yOSON.AppCore.runModule('moduleA1');
82 | yOSON.AppCore.runModule('moduleB1');
83 | });
84 |
85 | xit('should be execute method from moduleB2 to moduleA2', function(done){
86 | var functionToBridge2 = jasmine.createSpy();
87 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
88 |
89 | yOSON.AppCore.addModule('moduleA2', function(Sb){
90 | return {
91 | init: function(){
92 | Sb.trigger('publicMethodInModuleB2');
93 | }
94 | }
95 | });
96 |
97 | yOSON.AppCore.addModule('moduleB2', function(Sb){
98 | var privateMethodB2 = function(){
99 | functionToBridge2();
100 | expect(functionToBridge2).toHaveBeenCalled();
101 | done();
102 | };
103 | return {
104 | init: function(){
105 | Sb.events(['publicMethodInModuleB2'], privateMethodB2 , this);
106 | }
107 | }
108 | });
109 |
110 | yOSON.AppCore.runModule('moduleA2');
111 | yOSON.AppCore.runModule('moduleB2');
112 | });
113 |
114 | xit('should be execute method with params from moduleB3 to moduleA3', function(done){
115 | var functionToBridge3 = jasmine.createSpy();
116 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
117 |
118 | yOSON.AppCore.addModule('moduleA3', function(Sb){
119 | return {
120 | init: function(){
121 | Sb.trigger('publicMethodInModuleB3', "hello", "world");
122 | }
123 | }
124 | });
125 |
126 | yOSON.AppCore.addModule('moduleB3', function(Sb){
127 | var privateMethodB3 = function(paramA, paramB){
128 | functionToBridge3(paramA, paramB);
129 | expect(functionToBridge3).toHaveBeenCalledWith(paramA, paramB);
130 | done();
131 | };
132 | return {
133 | init: function(){
134 | Sb.events(['publicMethodInModuleB3'], privateMethodB3 , this);
135 | }
136 | }
137 | }, [ dependence ]);
138 |
139 | yOSON.AppCore.runModule('moduleA3');
140 | yOSON.AppCore.runModule('moduleB3');
141 | });
142 |
143 | xit('should be execute method with params from moduleB4 to moduleA4 and moduleC4', function(done){
144 | var functionToBridge4 = jasmine.createSpy();
145 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
146 |
147 | var dataCount = {
148 | index: 0,
149 | increment: function(){
150 | this.index+=1;
151 | }
152 | }
153 | yOSON.AppCore.addModule('moduleA4', function(Sb){
154 | return {
155 | init: function(){
156 | Sb.trigger('publicMethodInModuleB4', "hello", "world",function(data){
157 | dataCount.increment();
158 | });
159 | }
160 | }
161 | });
162 |
163 | yOSON.AppCore.addModule('moduleC4', function(Sb){
164 | return {
165 | init: function(){
166 | Sb.trigger('publicMethodInModuleB4', "hello2", "world2",function(data){
167 | expect(data.index).toEqual(2);
168 | done();
169 | });
170 | }
171 | }
172 | });
173 |
174 | yOSON.AppCore.addModule('moduleB4', function(Sb){
175 | var privateMethodB4 = function(paramA, paramB, callback){
176 | functionToBridge4(paramA, paramB);
177 | callback.call(this, dataCount);
178 | };
179 | return {
180 | init: function(){
181 | Sb.events(['publicMethodInModuleB4'], privateMethodB4 , this);
182 | }
183 | }
184 | }, [ dependence ]);
185 |
186 | yOSON.AppCore.runModule('moduleB4');
187 | yOSON.AppCore.runModule('moduleA4');
188 | yOSON.AppCore.runModule('moduleC4');
189 | });
190 | });
191 | });
192 |
--------------------------------------------------------------------------------
/test/spec/SpecDependency.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/dependency.js'
3 | ],
4 | function(Dependency){
5 | describe('Dependency Component', function(){
6 | var utils, array, status, dependencyObjTest, successDependenceUrl, failDependenceUrl;
7 |
8 | beforeEach(function(){
9 | var status = "";
10 | dependencyObjTest = null;
11 | successDependenceUrl = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
12 | failDependenceUrl = "http://holamundooo.com/demo.js";
13 | });
14 |
15 | it('should be a success request', function(done){
16 | var successCallback = jasmine.createSpy();
17 | dependencyObjTest = new Dependency(successDependenceUrl);
18 | dependencyObjTest.request({
19 | onReady: function(){
20 | successCallback();
21 | expect(successCallback).toHaveBeenCalled();
22 | done();
23 | }
24 | });
25 | });
26 |
27 | it('should be a fail request', function(done){
28 | var failCallBack = jasmine.createSpy();
29 | dependencyObjTest = new Dependency(failDependenceUrl);
30 | dependencyObjTest.request({
31 | onError: function(){
32 | failCallBack();
33 | expect(failCallBack).toHaveBeenCalled();
34 | done();
35 | }
36 | });
37 | });
38 |
39 | describe('Callbacks', function(){
40 | var callbacks;
41 |
42 | beforeEach(function(){
43 | callbacks = {
44 | onRequest: jasmine.createSpy(),
45 | onReady: jasmine.createSpy(),
46 | onError: jasmine.createSpy()
47 | };
48 | });
49 |
50 | it('should be execute when the state is on request', function(done){
51 | dependencyObjTest = new Dependency(successDependenceUrl);
52 | dependencyObjTest.request({
53 | onRequest: function(){
54 | callbacks.onRequest();
55 | expect(callbacks.onRequest).toHaveBeenCalled();
56 | done();
57 | }
58 | });
59 | });
60 |
61 | it('should be execute when the state is on ready', function(done){
62 | dependencyObjTest = new Dependency(successDependenceUrl);
63 | dependencyObjTest.request({
64 | onReady: function(){
65 | callbacks.onReady();
66 | expect(callbacks.onReady).toHaveBeenCalled();
67 | done();
68 | }
69 | });
70 | });
71 |
72 | it('should be execute when the state is on ready', function(done){
73 | dependencyObjTest = new Dependency(successDependenceUrl);
74 | dependencyObjTest.request({
75 | onReady: function(instanceLoaded){
76 | expect(instanceLoaded).not.toBeUndefined();
77 | done();
78 | }
79 | });
80 | });
81 |
82 | it('should be execute when the state is on Error', function(done){
83 | dependencyObjTest = new Dependency(failDependenceUrl);
84 | dependencyObjTest.request({
85 | onError: function(){
86 | callbacks.onError();
87 | expect(callbacks.onError).toHaveBeenCalled();
88 | done();
89 | }
90 | });
91 | });
92 | });
93 | });
94 | });
95 |
--------------------------------------------------------------------------------
/test/spec/SpecDependencyManager.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/single-promise.js',
3 | '../../src/comps/dependency.js',
4 | '../../src/managers/dependency.js'
5 | ],
6 | function(SinglePromise, Dependency, DependencyManager){
7 | describe("DependencyManager Component", function(){
8 | var versionUrl,
9 | staticHost,
10 | urlTest,
11 | objDependencyManager;
12 |
13 | beforeEach(function(){
14 | staticHost = "http://stat.host.com/";
15 | versionUrl = "?v12022008";
16 | objDependencyManager = new DependencyManager();
17 | });
18 |
19 | it('should be set the url of static server', function(){
20 | objDependencyManager.setStaticHost(staticHost);
21 |
22 | currentStaticHost = objDependencyManager.getStaticHost();
23 | expect(currentStaticHost).toEqual(staticHost);
24 | });
25 |
26 | it('should be set the version url', function(){
27 | objDependencyManager.setVersionUrl(versionUrl);
28 |
29 | currentVersion = objDependencyManager.getVersionUrl();
30 | expect(currentVersion).toEqual(versionUrl);
31 | });
32 |
33 | describe("Dealing the url of dependency", function(){
34 |
35 | var urlOfOtherSite,
36 | urlSelfSite;
37 |
38 | beforeEach(function(){
39 | urlOfOtherSite = "http://st.host.pe/js/jq.demo.js";
40 | urlOfOtherSiteWithRelativeProtocol = "//st.host.pe/js/jq.demo.js";
41 | urlSelfSite = "libs/js/jq.demo.js";
42 |
43 | objDependencyManager.setVersionUrl(versionUrl);
44 | objDependencyManager.setStaticHost(staticHost);
45 | });
46 |
47 | it('should be transform the url when come with http protocol', function(){
48 | var urlTransformed = objDependencyManager.transformUrl(urlOfOtherSite);
49 | expect(urlOfOtherSite).toEqual(urlTransformed);
50 | });
51 |
52 | it('should be transform the url when come with relative protocol (//)', function(){
53 | var urlTransformed = objDependencyManager.transformUrl(urlOfOtherSiteWithRelativeProtocol);
54 | expect(urlOfOtherSiteWithRelativeProtocol).toEqual(urlTransformed);
55 | });
56 |
57 | it('should be transform the url when come with self server', function(){
58 | versionUrl = "?v12022008";
59 | objDependencyManager.setVersionUrl(versionUrl);
60 | var urlTransformed = objDependencyManager.transformUrl(urlSelfSite);
61 | var urlExpected = "http://stat.host.com/libs/js/jq.demo.js?v12022008";
62 | expect(urlExpected).toEqual(urlTransformed);
63 | });
64 |
65 | it('should be generate the unique id by url', function(){
66 | var urlDummy = "stat_host_com_libs_js_jq_demo_js";
67 | var id = objDependencyManager.generateId(urlDummy);
68 | expect(id).toEqual(urlDummy);
69 | });
70 |
71 | describe('sanitize the url entered', function(){
72 | var urlExpected = null;
73 | beforeEach(function(){
74 | urlExpected = staticHost + "js/dist/libs/fancybox/source/helpers/jquery.fancybox-buttons.js" + versionUrl;
75 | });
76 | it('should be validate the url without double slashes', function () {
77 | var urlGood = staticHost + "js/dist/libs/fancybox/source/helpers/jquery.fancybox-buttons.js" + versionUrl;
78 | var urlDummy = objDependencyManager.sanitizeDoubleSlashes(urlGood);
79 | expect(urlDummy).toEqual(urlExpected);
80 | });
81 | it('should be validate the url with double slashes', function () {
82 | var urlWrong1 = staticHost + "/js/dist/libs/fancybox/source/helpers/jquery.fancybox-buttons.js" + versionUrl;
83 | var urlDummy = objDependencyManager.sanitizeDoubleSlashes(urlWrong1);
84 | expect(urlDummy).toEqual(urlExpected);
85 | });
86 | it('should be validate the url with double slashes', function () {
87 | var urlWrong2 = staticHost + "//js/dist/libs///fancybox/source/helpers/jquery.fancybox-buttons.js" + versionUrl;
88 | var urlDummy = objDependencyManager.sanitizeDoubleSlashes(urlWrong2);
89 | expect(urlDummy).toEqual(urlExpected);
90 | });
91 | });
92 |
93 | });
94 |
95 | it('should be append a dependency ', function(done){
96 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
97 | objDependencyManager.addScript(dependence).then(function(){
98 | expect(true).toBe(true);
99 | done();
100 | });
101 | });
102 |
103 | xit('should be validate when append a dependency already registered', function(){
104 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
105 | objDependencyManager.addScript(dependence);
106 | expect(objDependencyManager.addScript(dependence)).toBe("the dependence already appended");
107 | });
108 |
109 | it('should be run the callback when the dependences are ready', function(done){
110 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js",
111 | onReady = jasmine.createSpy();
112 |
113 | objDependencyManager.ready([dependence], function(){
114 | onReady();
115 | expect(onReady).toHaveBeenCalled();
116 | done();
117 | });
118 |
119 | });
120 |
121 | xit('should be dont run the callback error when the dependence return an error', function(done){
122 | var dependence = "http://helloworld.cc/js/wrongscripthellloworld.js",
123 | onNotAvaliable = jasmine.createSpy();
124 |
125 | objDependencyManager.addScript(dependence).then(function(){}, function(){
126 | onNotAvaliable();
127 | expect(onNotAvaliable).toHaveBeenCalled();
128 | done();
129 | });
130 |
131 | });
132 |
133 | it('should be get the dependence self', function(){
134 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
135 |
136 | objDependencyManager.addScript(dependence);
137 | var resultDependence = objDependencyManager.getDependency(dependence);
138 | expect(resultDependence instanceof Dependency).toBeTruthy();
139 | });
140 |
141 | it('should be return if the dependence its already in the collection of the manager', function(){
142 | var dependence = "http://cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js";
143 |
144 | objDependencyManager.addScript(dependence);
145 | var idOfDependence = objDependencyManager.generateId(dependence);
146 | var resultDependence = objDependencyManager.alreadyInCollection(idOfDependence);
147 | expect(resultDependence instanceof Dependency).toBeTruthy();
148 | });
149 |
150 |
151 | });
152 | });
153 |
--------------------------------------------------------------------------------
/test/spec/SpecLoader.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/loader.js',
3 | '../scripts/schema-demo.js'
4 | ],
5 | function(Loader, SchemaDemo){
6 | describe('LoaderComp', function(){
7 | var objLoader;
8 |
9 | beforeEach(function(){
10 | objLoader = new Loader(SchemaDemo);
11 | });
12 |
13 | it('should run the allModules node', function(){
14 | var allModules = jasmine.createSpy("allModules");
15 | SchemaDemo.modules.allModules = allModules;
16 |
17 | objLoader.init();
18 | expect(allModules).toHaveBeenCalled();
19 | });
20 |
21 | it('should run the default module', function(){
22 | var defaultModule = jasmine.createSpy("defaultModule");
23 | SchemaDemo.modules.byDefault = defaultModule;
24 |
25 | objLoader.init();
26 | expect(defaultModule).toHaveBeenCalled();
27 | });
28 |
29 | it('should run the allControllers node', function(){
30 | var allControllers = jasmine.createSpy("allControllers");
31 | SchemaDemo.modules.user.allControllers = allControllers;
32 |
33 | objLoader.init('user');
34 | expect(allControllers).toHaveBeenCalled();
35 | });
36 |
37 | it('should run the default controller by module application', function(){
38 | var defaultController = jasmine.createSpy("defaultController");
39 | SchemaDemo.modules.user.controllers.byDefault = defaultController;
40 |
41 | objLoader.init('user');
42 | expect(defaultController).toHaveBeenCalled();
43 | });
44 |
45 | it('should run the allActions of index controller by module application', function(){
46 |
47 | var allActions = jasmine.createSpy("allActions");
48 | SchemaDemo.modules.user.controllers.home.allActions = allActions;
49 | objLoader.init('user', 'home');
50 | expect(allActions).toHaveBeenCalled();
51 | });
52 |
53 | it('should run the default action of index controller by module application', function(){
54 |
55 | var defaultAction = jasmine.createSpy("defaultAction");
56 | SchemaDemo.modules.user.controllers.home.actions.byDefault = defaultAction;
57 | objLoader.init('user', 'home');
58 | expect(defaultAction).toHaveBeenCalled();
59 | });
60 |
61 | it('should run the index action of index controller by module application', function(){
62 |
63 | var indexAction = jasmine.createSpy("indexAction");
64 | SchemaDemo.modules.user.controllers.home.actions.index = indexAction;
65 | objLoader.init('user', 'home', 'index');
66 | expect(indexAction).toHaveBeenCalled();
67 | });
68 |
69 | });
70 | });
71 |
--------------------------------------------------------------------------------
/test/spec/SpecModular.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/modular.js'
3 | ],
4 | function(Modular){
5 | describe('specModular', function(){
6 | var objModular, moduleName, moduleSelf;
7 |
8 | beforeEach(function(){
9 | objModular = new Modular();
10 | moduleSelf = function(){
11 | var privateMethodA = function(){
12 |
13 | };
14 | return {
15 | init: jasmine.createSpy()
16 | }
17 | };
18 | });
19 |
20 | it('should be create a module', function(){
21 | objModular.create(moduleSelf);
22 | expect(true).toBeTruthy();
23 | });
24 |
25 | it("should be run the module", function(){
26 | objModular.create(moduleSelf);
27 | objModular.start();
28 | expect(objModular.getStatusModule()).toEqual('run');
29 | });
30 |
31 | it("should be setting the module status", function(){
32 | objModular.create(moduleSelf);
33 | objModular.setStatusModule('ready');
34 | expect(objModular.getStatusModule()).toEqual('ready');
35 | });
36 |
37 | it("should be append a method to pass the definition", function(){
38 | var methodToBridge = jasmine.createSpy();
39 | objModular = new Modular({
40 | "dummy": methodToBridge
41 | });
42 | objModular.create(function(objBridge){
43 | return {
44 | init: function(){
45 | objBridge.dummy();
46 | }
47 | }
48 | });
49 |
50 | spyOn(objModular, 'start').and.callThrough();
51 | objModular.start();
52 | expect(methodToBridge).toHaveBeenCalled();
53 | });
54 |
55 | describe("Callbacks", function(){
56 | var callbacks;
57 |
58 | beforeEach(function(){
59 | callbacks = {
60 | onCreated: jasmine.createSpy(),
61 | onRun: jasmine.createSpy(),
62 | onError: jasmine.createSpy()
63 | };
64 | });
65 |
66 | it("should be execute when its created", function(done){
67 | var objModular = new Modular({},{
68 | onCreated: function(){
69 | callbacks.onCreated();
70 | expect(callbacks.onCreated).toHaveBeenCalled();
71 | done();
72 | }
73 | });
74 | objModular.create(function(){
75 | return {
76 | init: function(){}
77 | }
78 | });
79 | });
80 |
81 | it("should be execute when its run", function(done){
82 | var objModular = new Modular({},{
83 | onRun: function(){
84 | callbacks.onRun();
85 | expect(callbacks.onRun).toHaveBeenCalled();
86 | done();
87 | }
88 | });
89 | objModular.create(function(){
90 | return {
91 | init: function(){}
92 | }
93 | });
94 | objModular.start();
95 | });
96 |
97 | it("should be execute when has an error", function(done){
98 | var objModular = new Modular({},{
99 | onError: function(){
100 | callbacks.onError();
101 | expect(callbacks.onError).toHaveBeenCalled();
102 | done();
103 | }
104 | });
105 | objModular.create(function(){
106 | return {
107 | init: function(){
108 | demo();
109 | }
110 | }
111 | });
112 | objModular.start();
113 | });
114 |
115 |
116 | })
117 |
118 | });
119 | });
120 |
--------------------------------------------------------------------------------
/test/spec/SpecModularManager.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/managers/modular.js',
3 | '../../src/comps/sequential.js'
4 | ],
5 | function(ModularManager, Sequential){
6 |
7 | describe('specModularManager', function(){
8 | var objModularManager, moduleName, moduleSelf;
9 |
10 | beforeEach(function(){
11 | objModularManager = new ModularManager();
12 | moduleName = "module-demo-test";
13 | moduleSelf = function(){
14 | var privateMethodA = function(){
15 |
16 | };
17 | return {
18 | publicMethodOfAModule: function(){
19 |
20 | },
21 | init: jasmine.createSpy()
22 | }
23 | };
24 | });
25 |
26 | it('should be add a module', function(){
27 | objModularManager.addModule(moduleName, moduleSelf);
28 | expect(objModularManager.getModule(moduleName)).toBeTruthy();
29 | });
30 |
31 | it("should be return true when the module exists", function(){
32 | objModularManager.addModule(moduleName, moduleSelf);
33 | expect(objModularManager.getModule(moduleName)).toBeTruthy();
34 | });
35 |
36 | it("should be run the module", function(){
37 | objModularManager.addModule(moduleName, moduleSelf);
38 | objModularManager.runModule(moduleName);
39 |
40 | var module = objModularManager.getModule(moduleName);
41 | expect(module.getStatusModule(moduleName)).toEqual('run');
42 | });
43 |
44 | it("should be setting the module status", function(){
45 | objModularManager.addModule(moduleName, moduleSelf);
46 | var module = objModularManager.getModule(moduleName);
47 | module.setStatusModule('ready');
48 | expect(module.getStatusModule(moduleName)).toEqual('ready');
49 | });
50 |
51 | it("should be append a method to bridge object", function(){
52 | var methodToBridge = jasmine.createSpy();
53 | objModularManager.addMethodToBrigde("dummy", methodToBridge);
54 |
55 | objModularManager.addModule('moduleA', function(objBridge){
56 | return {
57 | init: function(){
58 | objBridge.dummy();
59 | }
60 | }
61 | });
62 |
63 | spyOn(objModularManager, 'runModule').and.callThrough();
64 | objModularManager.runModule('moduleA');
65 | expect(methodToBridge).toHaveBeenCalled();
66 | });
67 |
68 | describe("Handler callbacks by status of module", function(){
69 | var moduleName;
70 |
71 | it("must be execute when it start", function(done){
72 | var callbackStatusStart = jasmine.createSpy();
73 | moduleName = "moduleDemoHandler";
74 |
75 | objModularManager.addModule(moduleName, function(done){
76 | return {init: function(){}}
77 | });
78 |
79 | var module = objModularManager.getModule(moduleName);
80 | module.setStatusModule("start");
81 |
82 | objModularManager.whenModuleHaveStatus(moduleName, "start", function(){
83 | callbackStatusStart();
84 | expect(callbackStatusStart).toHaveBeenCalled();
85 | done();
86 | });
87 |
88 | objModularManager.runModule(moduleName);
89 |
90 | });
91 |
92 | it("must be execute when its run", function(done){
93 | var callbackStatusRun = jasmine.createSpy();
94 | moduleName = "moduleDemoHandler2";
95 |
96 | objModularManager.addModule(moduleName, function(){
97 | return {init: function(){}}
98 | });
99 |
100 | objModularManager.runModule(moduleName);
101 | objModularManager.whenModuleHaveStatus(moduleName, "run", function(){
102 | callbackStatusRun();
103 | expect(callbackStatusRun).toHaveBeenCalled();
104 | done();
105 | });
106 | });
107 | });
108 |
109 | describe("Executing a synchronous mode", function(){
110 | var runModule, syncModule, runSequence, moduleNames, objSequential;
111 | beforeEach(function(){
112 | moduleNames = ["module-1st", "module-2nd", "module-3rd"];
113 | runSequence = [];
114 | objSequential = new Sequential();
115 |
116 | objModularManager.addModule(moduleNames[0], function(){
117 | return {
118 | init: function(){
119 | runSequence.push("a");
120 | }
121 | }
122 | });
123 |
124 | objModularManager.addModule(moduleNames[2], function(){
125 | return {
126 | init: function(){
127 | runSequence.push("c");
128 | }
129 | }
130 | });
131 |
132 | objModularManager.addModule(moduleNames[1], function(){
133 | return {
134 | init: function(){
135 | runSequence.push("b");
136 | }
137 | }
138 | });
139 |
140 | });
141 |
142 | it("Must be execute in order", function(){
143 | objSequential.inQueue(function(next){
144 | objModularManager.runModule(moduleNames[0]);
145 | next();
146 | }).inQueue(function(next){
147 | objModularManager.runModule(moduleNames[1]);
148 | next();
149 | }).inQueue(function(next){
150 | objModularManager.runModule(moduleNames[2]);
151 | next();
152 | });
153 | expect(runSequence).toEqual(['a','b', 'c']);
154 | });
155 | });
156 |
157 | describe("Listen Events", function(){
158 | var moduleListener = {};
159 | beforeEach(function(){
160 | moduleListener.name = "moduleListener";
161 | moduleListener.self = function(){
162 | return {
163 | init: function(){}
164 | }
165 | };
166 | });
167 |
168 | it("should be listen the onCreate callback", function(done){
169 | var spyOnCreated = jasmine.createSpy();
170 | var moduleName = moduleListener.name + "onCreate";
171 | objModularManager.listenEvent(moduleName, "onCreated", function(){
172 | spyOnCreated();
173 | expect(spyOnCreated).toHaveBeenCalled();
174 | done();
175 | });
176 | objModularManager.addModule(moduleName, moduleListener.self);
177 | });
178 |
179 | it("should be listen the onRun callback", function(done){
180 | var spyOnRun = jasmine.createSpy();
181 | var moduleName = moduleListener.name + "onRun";
182 | objModularManager.listenEvent(moduleName, "onRun", function(){
183 | spyOnRun();
184 | expect(spyOnRun).toHaveBeenCalled();
185 | done();
186 | });
187 | objModularManager.addModule(moduleName, moduleListener.self);
188 | objModularManager.runModule(moduleName);
189 | });
190 |
191 | it("should be listen the onError callback", function(done){
192 | var spyOnError = jasmine.createSpy();
193 | var moduleName = moduleListener.name + "onError";
194 | objModularManager.listenEvent(moduleName, "onError", function(){
195 | spyOnError();
196 | expect(spyOnError).toHaveBeenCalled();
197 | done();
198 | });
199 | objModularManager.addModule(moduleName, function(){
200 | return {
201 | init: function(){
202 | frikiFunction();
203 | }
204 | }
205 | });
206 | objModularManager.runModule(moduleName);
207 | });
208 |
209 |
210 | });
211 |
212 | });
213 | });
214 |
--------------------------------------------------------------------------------
/test/spec/SpecSinglePromise.js:
--------------------------------------------------------------------------------
1 | define([
2 | '../../src/comps/single-promise.js'
3 | ],
4 | function(SinglePromise){
5 | describe('SinglePromise Component', function(){
6 | var objSinglePromiseTest, dummyFunction, randomTimeout;
7 |
8 | beforeEach(function(){
9 | randomTimeout = Math.ceil(Math.random() * 1000) + 1;
10 | objSinglePromiseTest = null;
11 | dummyFunction = function(){};
12 | });
13 |
14 | it('should be execute the success callback when invoke "then"', function(done){
15 | var successCallback = jasmine.createSpy();
16 | dummyFunction = function(){
17 | objSinglePromiseTest = new SinglePromise();
18 | setTimeout(function(){
19 | objSinglePromiseTest.done();
20 | }, randomTimeout);
21 | return objSinglePromiseTest;
22 | };
23 | dummyFunction().then(function(){
24 | successCallback();
25 | expect(successCallback).toHaveBeenCalled();
26 | done();
27 | });
28 | });
29 |
30 |
31 | it('should be execute the success callback with params when invoke "then"', function(done){
32 | var message = "data";
33 | dummyFunction = function(){
34 | objSinglePromiseTest = new SinglePromise();
35 | setTimeout(function(){
36 | objSinglePromiseTest.done(message);
37 | }, randomTimeout);
38 | return objSinglePromiseTest;
39 | };
40 | dummyFunction().then(function(paramMessage){
41 | expect(message).toEqual(paramMessage);
42 | done();
43 | });
44 | });
45 |
46 | it('should be execute the fail callback when invoke "then"', function(done){
47 | var failCallback = jasmine.createSpy();
48 | dummyFunction = function(){
49 | objSinglePromiseTest = new SinglePromise();
50 | setTimeout(function(){
51 | objSinglePromiseTest.fail();
52 | }, randomTimeout);
53 | return objSinglePromiseTest;
54 | };
55 | dummyFunction().then(function(){},function(){
56 | failCallback();
57 | expect(failCallback).toHaveBeenCalled();
58 | done();
59 | });
60 | });
61 |
62 | });
63 | });
64 |
--------------------------------------------------------------------------------
/validate-commit-message.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | /**
3 | * Script to validate the format of commit
4 | * Instalation:
5 | * ~ cd
6 | * ~ ln -s ../../validate-commit-message.js .git/hooks/commit-msg
7 | */
8 |
9 | 'use strict';
10 |
11 | var fs = require('fs');
12 | var util = require('util');
13 |
14 | var MAX_LENGTH = 100;
15 | var PATTERN = /^(?:fixup!\s*)?(\w*)(\(([w\$\.\*/-]*)\))?\: (.*)$/;
16 | var IGNORED = /^WIP\:/;
17 | var TYPES ={
18 | feat: true,
19 | fix: true,
20 | docs: true,
21 | style: true,
22 | refactor: true,
23 | perf: true,
24 | test: true,
25 | chore: true,
26 | revert: true
27 | };
28 |
29 | var MSG = {
30 | IGNORED: "Commit message validation ignored.",
31 | ERROR:{
32 | MAX_LENGTH: 'Is longer than %d characters !',
33 | PATTERN: 'Does not match "(): " ! was:',
34 | TYPES: '"%s" is not allowed type !'
35 | }
36 | };
37 |
38 | var log = console.log;
39 | var logError = function(){
40 | console.error('INVALID COMMIT MSG:' + util.format.apply(null, arguments));
41 | };
42 |
43 | var isMessageIgnored = function(message){
44 | return IGNORED.test(message);
45 | };
46 |
47 | var validateMessage = function(message){
48 | var isValid = true;
49 | if(isMessageIgnored(message)){
50 | log(MSG.IGNORED);
51 | return true;
52 | }
53 |
54 | if(message.length > MAX_LENGTH){
55 | logError(, MAX_LENGTH);
56 | }
57 |
58 | var match = PATTERN.exec(message);
59 |
60 | if(!match){
61 | logError(MSG.ERROR.PATTERN + message);
62 | return false;
63 | }
64 |
65 | var type = match[1];
66 | var scope = match[3];
67 | var subject = match[4];
68 |
69 | if(!TYPES.hasOwnProperty(type)){
70 | logError(MSG.ERROR.TYPES, type);
71 | return false;
72 | }
73 | // Some more ideas, do want anything like this ?
74 | // - allow only specific scopes (eg. fix(docs) should not be allowed ?
75 | // - auto correct the type to lower case ?
76 | // - auto correct first letter of the subject to lower case ?
77 | // - auto add empty line after subject ?
78 | // - auto remove empty () ?
79 | // - auto correct typos in type ?
80 | // - store incorrect messages, so that we can learn
81 | return isValid;
82 | };
83 |
84 | var firstLineFromBuffer = function(buffer){
85 | return buffer.toString().split('\n').shift();
86 | };
87 |
88 | //publish for testing
89 | exports.validateMessage = validateMessage;
90 |
91 | //hack start if not run by jasmine :-D
92 | if(process.argv.join('').indexOf('jasmine-node') === -1){
93 | var commitMsgFile = process.argv[2];
94 | var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs');
95 |
96 | fs.readFile(commitMsgFile, function(err, buffer){
97 | var msg = firstLineFromBuffer(buffer);
98 |
99 | if(!validateMessage(msg)){
100 | fs.appendFile(incorrectLogFile, msg + '\n', function(){
101 | process.exit(0);
102 | });
103 | } else {
104 | process.exit(0);
105 | }
106 | });
107 | }
108 |
--------------------------------------------------------------------------------