Angular v1 - Module's config not called via Lazyload - oclazyload

Lazyload Config in Parent App
{
name: "lazyload-module",
files: ["http://link_to_lazyload_module_js"],
reconfig: true,
rerun: true
},
Module Code to be LazyLoaded
`
(function() {
var __MODULE_NAME = "lazyload-module";
var app = function(angular) {
"use strict";
angular.module(__MODULE_NAME, ["oc.lazyload"]).config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
debug: true,
events: true,
modules: [{
name : 'module1_in_lazyload_module',
files : ["resource_link_11","resource_link_12"]
},{
name : 'module2_in_lazyload_module',
files : ["resource_link_21","resource_link_22"]
}]
});
}]);
angular.module(__MODULE_NAME, __DEPS["module_deps"]).run(function($ocLazyLoad){
$ocLazyLoad.load(["module1_in_lazyload_module","module2_in_lazyload_module"]).then(function (data) {
});
});
return angular.module(__MODULE_NAME);
};
if ((typeof window !== "undefined" && window !== null ? window.angular : void 0) != null) {
app(window.angular);
} else if (typeof require === "function") {
var angular = require("angular");
app(angular);
} else {
throw new Error("Could not find angular on window nor via require()");
}
if (typeof module !== "undefined" && module !== null) {
module.exports = __MODULE_NAME;
}
}).call(this);
`
Issue
the config and run in the lazyload-module is not getting called when the module itself is loaded via lazyload from parent app.
What is the issue/mistake here ? Basically what am trying to do is recursively lazyload modules on demand and not everything in the parent app.
Config and run of lazyload-module is called when this is directly loaded in Parent App

Related

ionic input file doesn't clear object

in my ionic app, I have in home.html file
:
<input type="file" (change)="onFileChange($event)" multiple />
and in .ts file
onFileChange(fileChangeEvent) {
this.file = fileChangeEvent.target.files[0];
if (typeof fileChangeEvent.target.files[1] !== 'undefined') {
this.file_2 = fileChangeEvent.target.files[1];
}
if (typeof fileChangeEvent.target.files[2] !== 'undefined') {
this.file_3 = fileChangeEvent.target.files[2];
}}async submitForm() {
let formData = new FormData();
formData.append("photo", this.file, this.file.name);
if (typeof this.file_2 !== 'undefined') {
formData.append("photo_2", this.file_2, this.file_2.name);
}
if (typeof this.file_3 !== 'undefined') {
formData.append("photo_3", this.file_3, this.file_3.name);
}
formData.append("nome_mercatino", this.nome_mercatino);
this.http.post("https://myserver/myphpfile.php", formData).subscribe((response) => {
console.log(response);
});
}`
to send from 1 to 3 image to server. When I send first time files, there is no problem, but, if I retry, changing for example, from 2 files, to only 1 file, when I send to server my file, also the second one from the previous sending, is re-sent. Why? How can I clear file object to send always the correct files?
i got the answer set all three files to undefined when you done.You are setting file_2 but in if condition it is failing and file_2 is not changing i think you got it?
onFileChange(fileChangeEvent) {
this.file = fileChangeEvent.target.files[0];
if (typeof fileChangeEvent.target.files[1] !== 'undefined') {
this.file_2 = fileChangeEvent.target.files[1];
}
if (typeof fileChangeEvent.target.files[2] !== 'undefined') {
this.file_3 = fileChangeEvent.target.files[2];
}}async submitForm() {
let formData = new FormData();
formData.append("photo", this.file, this.file.name);
if (typeof this.file_2 !== 'undefined') {
formData.append("photo_2", this.file_2, this.file_2.name);
}
if (typeof this.file_3 !== 'undefined') {
formData.append("photo_3", this.file_3, this.file_3.name);
}
formData.append("nome_mercatino", this.nome_mercatino);
this.http.post("https://myserver/myphpfile.php", formData).subscribe((response) => {
console.log(response);
this.file_1=undefined;
this.file_2=undefined;
this.file_3=undefined;
});

"exports is not defined" - using Foundation plugins with Babel

I am new to foundation, and Babel, but have followed the docs and can't figure out what's wrong.
I am using Laravel Mix as part of my build system, which is basically a wrapper for Webpack. Here is my webpack.mix.js:
mix.babel([
'bower_components/jquery/dist/jquery.js',
'bower_components/foundation-sites/js/foundation.dropdownMenu.js',
'resources/assets/themes/'+themeInfo.name+'/js/app.js'
], 'public/themes/'+themeInfo.name+'/js/all.js');
The build process appears to run just fine, however I am getting "Uncaught ReferenceError: exports is not defined" in the browser.
At the top of all.js I can see the following JS:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DropdownMenu = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = require("jquery");
var _jquery2 = _interopRequireDefault(_jquery);
var _foundationUtil = require("./foundation.util.keyboard");
var _foundationUtil2 = require("./foundation.util.nest");
var _foundationUtil3 = require("./foundation.util.box");
var _foundationUtil4 = require("./foundation.util.core");
var _foundation = require("./foundation.plugin");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
To test, I declared the exports variable `var exports = {};` at the top of the file, which only then resulted in the error "Uncaught ReferenceError: require is not defined" pointing to the "var _jquery = require("jquery");" declaration.
I suspect I'm not understanding how Babel/Foundation plugins work properly, so any help would be appreciated please.
BTW I have the following in my .babelrc file, and have installed the preset using npm install babel-preset-es2015 --save-dev:
{
"presets": ["es2015"]
}

Firefox extension: Refer to object defined in bootstrap.js from XUL file

I'm trying to contribute to a Firefox extension I use, but I have no idea what I'm doing :)
I've got a dialog powered by a XUL document to gather some data from the user. That's all fine and good. But when the user confirms the dialog, I need to call a function defined on an object that's defined in my bootstrap.js file. Is that possible to do directly? e.g., in the XUL file:
<prefpanes id="my-pane" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script>
function myCallback() {
PassFF.myAction(); // PassFF is undefined here
};
</script>
<prefpane>
<button id="my-button" oncommand="myCallback();" />
</prefpane>
</prefpanes>
If that's not possible, is it possible to register a callback when I open the document in the first place? Something like this:
var dialog = window.openDialog("chrome://passff/content/mypane.xul",
"my_pane_name",
"chrome,titlebar,toolbar,modal");
dialog.addEventListener('close', function(event) {
PassFF.myAction(); // PassFF is defined here, but the event doesn't fire
});
I've tried things like importing the bootstrap.js script in my XUL document with another script tag, adding another "content" line to the manifest to expose the file, different events (unload, command, click) but couldn't figure out any of these approaches either.
Any tips?
You can use, for example, platform observer mechanics.
this is "signals.js" file (module):
let EXPORTED_SYMBOLS = ["addSignalListener", "removeSignalListener", "emitSignal", "signalNamePrefix"];
const {utils:Cu, classes:Cc, interfaces:Ci, results:Cr} = Components;
function genUUID () {
let uuidgen = Cc["#mozilla.org/uuid-generator;1"].createInstance(Ci.nsIUUIDGenerator);
if (!uuidgen) throw new Error("no UUID generator available!");
return uuidgen.generateUUID().toString().replace(/[^-a-z0-9]/ig, "");
}
const signalNamePrefix = "signal-"+genUUID()+"-";
const obs = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
let observers = {};
function addSignalListener (name, cback) {
if (typeof(name) !== "string" || !name) throw new Error("invalid signal name");
if (typeof(cback) !== "function") throw new Error("callback function expected");
// check if already here
if (cback in observers) {
let names = observers[cback];
if (name in names) return; // nothing to do
} else {
observers[cback] = {};
}
let observer = {
observe: function (subject, topic, data) {
topic = topic.substr(signalNamePrefix.length); // remove prefix
if (data && data.length) {
try {
data = JSON.parse(data);
} catch (e) {
Cu.reportError(e);
return;
}
} else {
data = null;
}
cback(topic, data);
},
};
obs.addObserver(observer, signalNamePrefix+name, false);
observers[cback][name] = observer;
}
function removeSignalListener (name, cback) {
if (typeof(name) !== "string" || !name) throw new Error("invalid signal name");
if (typeof(cback) !== "function") throw new Error("callback function expected");
// find observer
let names = observers[cback];
if (names === undefined) return; // nothing to do
if (!(name in names)) return; // nothing to do
try { obs.removeObserver(observers[cback][name], name); } catch (e) {}
}
function emitSignal (name, data) {
if (typeof(name) !== "string" || !name) throw new Error("invalid signal name");
data = (typeof(data) === "undefined" ? null : (data !== null ? JSON.stringify(data) : null));
obs.notifyObservers(null, signalNamePrefix+name, data);
}
sample use:
Components.utils.import("chrome://myext/content/signals.js");
dump(signalNamePrefix+"\n");
addSignalListener("mysignal", function (signame, data) {
dump("MYSIGNAL("+signame+"): "+data+"\n");
for (let [k, v] of Iterator(data)) dump(" ["+k+"]=["+v+"]\n");
});
emitSignal("mysignal", {any:42, data:[669], here:"wow!"});
here just import "signals.js" in your "bootstrap.js", and add signal listener. then import "signals.js" in your dialog js, and emit signal with the data you need.

How to keep session in multipage angular application?

I am having single page application with user authentication and there is no problem sharing session information there.
However I have part of site where are static pages where I would like just to include session information (logged in user, or login form). How I can share session information between two apps?
I would recommend creating a service that wraps localStorage or other apis to store persistent data. Here is an example using a localStorage implementation.
This implementation is synchronous but if I would use websql like or even server db then I would refactor it to use promises to return the storage object.
Controller
var demo = angular.module('demo', [ 'appStorage' ]);
demo.controller('AppStorageController', [ '$scope', 'appStorage',
function($scope, appStorage) {
appStorage('MyAppStorage', 'myAppStorage', $scope);
} ]);
HTML
<div ng-controller="AppStorageController">
<p>Local Storage: {{myAppStorage}}</p>
<p>
Username: <input type="text" ng-model="myAppStorage.username"></input>
</p>
<p>
Remember me: <input type="checkbox"
ng-model="myAppStorage.rememberMe"></input>
</p>
</div>
JS
angular.module('appStorage', []).factory('appStorage',
[ '$window', function($window) {
var appStorages = {};
var api = undefined;
if ($window.localStorage) {
api = {
set : function(name, value) {
$window.localStorage.setItem(name, JSON.stringify(value));
},
get : function(name) {
var str = $window.localStorage.getItem(name);
var val = {};
try {
val = str ? JSON.parse(str) : {};
}
catch (e) {
console.log('Parse error for localStorage ' + name);
}
return val;
},
clear : function() {
$window.localStorage.clear();
}
};
}
// possibly support other
if (!api) {
throw new Error('Could not find suitable storage');
}
return function(appName, property, scope) {
if (appName === undefined) {
throw new Error('appName is required');
}
var appStorage = appStorages[appName];
var update = function() {
api.set(appName, appStorage);
};
var clear = function() {
api.clear(appName);
};
if (!appStorage) {
appStorage = api.get(appName);
appStorages[appName] = appStorage;
update();
}
var bind = function(property, scope) {
scope[property] = appStorage;
scope.$watch(property, function() {
update();
}, true);
};
if (property !== undefined && scope !== undefined) {
bind(property, scope);
}
return {
get : function(name) {
return appStorage[name];
},
set : function(name, value) {
appStorage[name] = value;
update();
},
clear : clear
};
};
} ]);

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources