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

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"]
}

Related

Vue - DOM is not updating when doing .sort() on array

I am trying to sort some JSON data using Vue. The data gets changed when checking via Vue console debugger, but the actual DOM doesn't get updated.
This is my Vue code:
Array.prototype.unique = function () {
return this.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
};
if (!Array.prototype.last) {
Array.prototype.last = function () {
return this[this.length - 1];
};
};
var vm = new Vue({
el: "#streetleague-news",
data: {
allItems: [],
itemTypes: [],
itemTypesWithHeading: [],
selectedType: "All",
isActive: false,
sortDirection: "newFirst",
paginate: ['sortedItems']
},
created() {
axios.get("/umbraco/api/NewsLibraryApi/getall")
.then(response => {
// JSON responses are automatically parsed.
this.allItems = response.data;
this.itemTypes = this.allItems.filter(function (x) {
return x.Tag != null && x.Tag.length;
}).map(function (x) {
return x.Tag;
}).unique();
});
},
computed: {
isAllActive() {
return this.selectedType === "All";
},
filteredItems: function () {
var _this = this;
return _this.allItems.filter(function (x) {
return _this.selectedType === "All" || x.Tag === _this.selectedType;
});
},
sortedItems: function () {
var _this = this;
var news = _this.filteredItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
return new Date(b.PostDate) - new Date(a.PostDate);
});
} else {
news.sort(function (a, b) {
return new Date(a.PostDate) - new Date(b.PostDate);
});
}
return news;
}
},
methods: {
onChangePage(sortedItems) {
// update page of items
this.sortedItems = sortedItems;
}
}
});
This is an HTML part:
<paginate class="grid-3 flex" name="sortedItems" :list="sortedItems" :per="12" ref="paginator">
<li class="flex" v-for="item in paginated('sortedItems')">
The bit that seems not to be working is the sortedItems: function () {....
Can anyone see why the DOM is not updating?
The most probable is that sort() method doesn't recognize Date object precedence. Use js timestamp instead:
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
});
}
Got there eventually - thanks for your help
sortedItems: function () {
var _this = this;
var news = _this.allItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
})
}
return news.filter(x => {
return _this.selectedType === "All" || x.Tag ===
_this.selectedType;
});
}

callback function wont run when its called

ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(callback) {
if(xml.readyState == 4 && xml.status == 200) {
callback();
}
}
xml.open(typ,url,true);
xml.send();
}
}
//Function being called
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php?email=email#email.com",function() {
alert(xml.responseText);
});
}
It throws the error saying:
Uncaught TypeError: callback is not a functionxml.onreadystatechange #
global.js:30
Any ideas?
I fixed it by passing the data variable through the onreadystatechange function and calling it in the callback function.
ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(data) {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}
}
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php? email=jonwcode#gmail.com",function(data){
alert(data);
});
}
Try like this:
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
callback();
}
};
Notice that the onreadystatechange function doesn't take any parameters whereas in your code you have passed it a parameter with the name callback which will override the callback variable from the outer scope.
UPDATE:
It looks like you have improperly scoped the xml variable and it isn't available in your AJAX callback. I strongly recommend you reading more about javascript variables scope. Here's how you could make the xml variable visible:
var xml = null;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xml == null) {
alert('Sorry, your browser doesn\'t seem to support AJAX - please upgrade to a modern browser');
} else {
xml.onreadystatechange = function() {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}

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.

nightwatch assert ALL elements, not ANY

I'm trying to test that, when the Submit button is clicked on an empty form, all the "please fill in this field" labels are displayed.
I'm doing so with this:
page.click('#btn_submit');
page.expect.element('#validation_label_required').to.be.visible;
where #validation_label_required is represented by the CSS selector:
input[required] ~ p.error-message-required
However, this test passes if ANY of the validation labels are visible. The test should only pass if they ALL are.
How can I achieve this?
You will need to create a custom assertion for that where you locate all elements by selenium commands and then loop to verify condition. It should look something like this
var util = require('util');
exports.assertion = function (elementSelector, expectedValue, msg) {
this.message = msg || util.format('Testing if elements located by "%s" are visible', elementSelector);
this.expected = expectedValue;
this.pass = function (value) {
return value === this.expected;
};
this.value = function (result) {
return result;
};
this.command = function (callback) {
var that = this.api;
this.api.elements('css selector',elementSelector, function (elements) {
elements.value.forEach(function(element){
that.elementIdDisplayed(element.ELEMENT,function(result){
if(!result.value){
callback(false);
}
});
});
callback(true);
});
return this;
};
};
I've just ended up with another custom assertion that check how many elements are visible by given css selector.
/**
* Check how many elements are visible by given css selector.
*
*/
var util = require('util');
exports.assertion = function(elementSelector, expectedCount, msg) {
this.message = msg || util.format('Asserting %s elements located by css selector "%s" are visible', expectedCount, elementSelector);
this.expected = expectedCount;
this.count = 0;
this.pass = function(value) {
return value === this.expected;
};
this.value = function(result) {
return this.count;
};
this.command = function(callback) {
var me = this, elcount = 0;
this.count = 0;
this.api.elements('css selector', elementSelector, function(elements) {
if(elements.value && elements.value.length > 0){
elcount = elements.value.length;
}else{
return callback(false);
}
elements.value.forEach(function(element) {
me.api.elementIdDisplayed(element.ELEMENT, function(result) {
if (result.value) {
me.count++;
}
elcount--;
if (elcount === 0) {
callback(me.count);
}
});
});
});
};
};

Exception nette-ajax extension error in IE8

I have a problem with an exception nette-ajax extension in IE8. Does anybody know, what does it mean and how fix it?
this.ext = function (name, callbacks, context) {
if (typeof name === 'object') {
inner.ext(name, callbacks);
} else if (callbacks === undefined) {
return inner.contexts[name];
} else if (!callbacks) {
$.each(['init', 'load', 'prepare', 'before', 'start', 'success', 'complete', 'error'], function (index, event) {
inner.on[event][name] = undefined;
});
inner.contexts[name] = undefined;
} else if (typeof name === 'string' && inner.contexts[name] !== undefined) {
throw "Cannot override already registered nette-ajax extension '" + name + "'.";
} else {
inner.ext(callbacks, context, name);
}
return this;
};
in console.log(name) is result redirect

Resources