I have the following logic using pnotify.js:
//File notification.js
define(['require','pnotify' ],
function(require,PNotify){
require( [ 'pnotify.nonblock', 'pnotify.desktop' ],function(){
PNotify.desktop.permission();
});
});
and in another file
//File notification2.js
define(['notification' ],
function(Notification){
return function(msg){
new PNotify({
title: 'Desktop Notice',
text: msg,
desktop: {
desktop: true
},
nonblock: {
nonblock: true
}
});
}
});
This is working fine, but I was wondering if there was a way to do this in only one file?
I am calling my function like this:
define([
'notification2'
], function(Notification){
//some code
var notif = Notification("hello");
//some code
Related
I am new to ReqireJs. I am trying to do the following:
I have a file(mymodule.js) with the following code:
require([
'jquery'
], function ($) {
var name;
$(document).ready(function() {
//do some load stuff
});
});
I am trying to include the file into some other file as follows:
require(['modules/mymodule.js']);
which works fine. My question is that how can I pass some parameters from require(['modules/mymodule.js']); into mymodules.js?
Thanks and regards.
I have found the solution here:
http://blog.novanet.no/4-strategies-for-passing-parameters-to-requirejs-modules/
I have used the code from 1st step from above link "Passing parameter to method" as follows:
define(
[
'jquery'
],
function($){
return {
sayHello: function(name){
alert("Hello " + name);
}
};
}
);
Then I have passed the parameter as follows:
require(['modules/mymodule.js'], function(mymodule){
mymodule.sayHello("World");
});
When I write the following code in jupyter opened from my system, it is working, but when I open it from another system it is not. The problem is with require(it is not running). I have put some consoles to see where it is stopping and it is running till console.log(require.s.contexts._.defined). I have checked the modules with this console and angular seems to be missing in this. Thanks in advance.
%%javascript
require.config({
paths: {
velocity: "https://cdn.jsdelivr.net/velocity/1.2.3/velocity.min",
interact: "https://cdn.jsdelivr.net/interact.js/1.2.6/interact.min",
angular: "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min"
},
shim: {
'angular': {
exports: 'angular'
}
}
});
function start_application(data) {
// console.log("data ready")
console.log(require.s.contexts._.defined)
require(['angular', 'jquery'], function(angular,$) {
console.log("require running")
$.ajax({url: "http://localhost:8889/tree/Jupyter_Angular/DQAForm.html",
success: function(result) {
// console.log("SUCCESS")
// console.log(result);
$("#DQAFormContainer").html(result)
var el = document.getElementById("dqaBrickContent");
if(angular.element(el).injector()){
angular.element(el).injector().get('$rootScope').$destroy()
}
var dqaBrick = angular.module('dqaBrick', []);
dqaBrick.controller('dqaBrickCtrl', ['$scope', function ($scope) {
$scope.myVariable = 'Starting new DQA Brick';
console.log($scope.myVariable);
$scope.showPanel = 1;
$scope.openPanel = function (panelNum) {
$scope.showPanel = panelNum;
// console.log(panelNum);
}
}]);
angular.element(document).ready(function() {
angular.bootstrap(el, ['dqaBrick']);
});
}
});
})
}
var callbacks = {
iopub : {
output : start_application
}
}
var kernel = IPython.notebook.kernel
kernel.execute('print("This is the starting")', callbacks)
I'm trying to use the node xmlbuilder module, and copied / pasted their code from here but I get a
Converting circular structure to JSON error.
I have no clue why this is happening, here is the code:
Route:
app.get('/api/qb', function(req, res) {
qbwc.test(req, function(result){
res.send(result);
});
});
Module:
exports.test = function(data, next) {
var obj = {
person: {
name: "John",
'#age': 35,
address: {
city: "Istanbul"
},
phone: [
{
'#text': "555-1234",
'#type': 'home'
}, {
'#text': "555-1235",
'#type': 'mobile'
}
],
id: function() {
return 42;
}
}
};
var root = builder.create(obj);
return next(root);
}
EDIT:
I also tried it with something very simple to test, same issue:
var obj = { name: 'smith'};
var root = builder.create(obj);
return next(root);
Ok so after a lot of hair pulling, it seems you need to call .end() on the process, I have no idea why they don't have this in the example.
Here is what you need to do:
...
var root = builder.create(obj);
root = root.end({pretty: false});
return next(root);
I'm trying to build a Chrome extension with TypeScript.
The setup is quite simple:
In manifest.json
{
"permissions": [
"webRequest",
"webRequestBlocking",
"tabs",
"storage",
"http://*/",
"https://*/*"
],
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "scripts/require.js", "scripts/require-cs.js",
"scripts/main.js", "scripts/contentscript.js" ],
"run_at": "document_end",
"all_frames": true
}],
}
In model.ts:
export class WebPage
{
private id: number;
private processed: boolean;
get Id() { return this.id; }
set Id(value: number) { this.id = value };
get Processed() { return this.processed; }
set Processed(value: boolean) { this.processed = value };
constructor(id: number)
{
this.id = id;
this.processed = false;
}
}
When compiled the resulting JavaScript starts with:
define(["require", "exports"], function (require, exports) {
var WebPage = (function ()
{
//Code omitted to keep the SO question short
}});
In main.ts:
(function ()
{
console.log("Executing main.js");
requirejs.config(
{
baseUrl: "scripts", paths: { "model" : "model" }
});
})();
In contentscript.ts:
import model = require("model");
console.log("Processing page");
var page = new model.WebPage(1);
page.Processed = true;
console.log("Done processing page");
When compiled the resulting JavaScript looks like this:
define(["require", "exports", "model"], function (require, exports, model) {
console.log("Processing page");
var page = new model.WebPage(1);
page.Processed = true;
console.log("Done processing page");
});
And finally in require-cs.js:
console.log("Executing requirejs-cs.js");
require.load = function (context, moduleName, url) {
console.log("require.load called");
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.extension.getURL(url) + '?r=' + (new Date()).getTime(), true);
xhr.onreadystatechange = function (e) {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("evaluating" + url)
eval(xhr.responseText);
context.completeLoad(moduleName);
}
};
xhr.send(null);
};
Which is what I found in all the other questions related to my issue.
All of this results in the following output when loading a page:
Uncaught Error: Mismatched anonymous define() module: function (require, exports, model) {
console.log("Processing page");
var page = new model.WebPage(1);
page.Processed = true;
console.log("Done processing page");
}
http://requirejs.org/docs/errors.html#mismatch
I've read those docs, I went through a lot of similar questions on SO,
but I haven't found anything that works for me yet.
Most questions deal with JavaScript specifically,
perhaps there is something missing on the TypeScript side of things?
Note: The TypeScript compiler is configured to use AMD.
The docs for the error message state:
Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.
As described in this question, it seems that if you use import in a type script, it will be turned into a module when compiled using AMD. So by including "scripts/contentscript.js" as a content script you are trying to load a module script without using the RequireJS API. You can try removing contentscript.js from the content_scripts entry in the manifest and adding the following to main.js:
requirejs(["contentscript"], function() {});
I'm trying to set up assetmanager
for my blog that has three modules
default
login
admin
I tried like
assets.json
{
"css": {
"app":{
"public/src/dist/default/css/dist.min.css": [
"public/src/assets/default/css/*.css"
]
},
"login":{
"public/src/dist/login/css/dist.min.css": [
"public/src/assets/default/css/*.css"
]
},
"admin":{
"public/src/dist/admin/css/dist.min.css": [
"public/src/assets/admin/css/*.css"
]
}
}
}
express.js
assetmanager.init({
js: assets.js,
css: assets.css,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'public'
});
// Add assets to local variables
app.use(function(req, res, next) {
res.locals({
assets: assetmanager.assets
});
next();
});
console.log(assetmanager.assets);
but console.log(assetmanager.assets);
give me a empty array []
so is there a way to manage assetmanager
with more than one module ?
the best way I found up to now
is like in my controllers:
'use strict';
var assetmanager = require('assetmanager');
exports.render = function(config) {
var assets = require(config.sroot+'/config/assets.json');
assetmanager.init({
js: assets.js.app,
css: assets.css.app,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'public'
});
return function(req, res) {
res.render('layouts/default', {appTitle:'ilwebdifabio',assets:assetmanager.assets});
}
};
but it's quite ugly and I have
duplicate code :(
END UP
There is no way to use assetmanager module
in different modules (login,default,admin).
Modules are automatically cached by the Node.js application upon first load. As such, repeated calls to require() - the global method that loads modules - will all result in a reference to the same cached object.
so you end up ie if you use in a module
to the have the dedicate assets in all other module so
I worked it out with :
'use strict';
var _ = require('lodash');
module.exports = function (path,route) {
var env = (process.env.NODE_ENV === 'production') ? 'production' : null;
var debug = (env !== 'production');
var data = require(path+'/config/assets.json');
var assets = {
css: [],
js: []
};
var getAssets = function (pattern) {
var files = [];
if (_.isArray(pattern)) {
_.each(pattern, function (path) {
files = files.concat(getAssets(path));
});
} else if (_.isString(pattern)) {
var regex = new RegExp('^(//)');
if (regex.test(pattern)) {
// Source is external
//For the / in the template against 404
files.push(pattern.substring(1));
} else {
files.push(pattern);
}
}
return files;
};
var getFiles = function () {
var current = data[route];
_.each(['css', 'js'], function (fileType) {
_.each(current[fileType], function (value, key) {
if (!debug) {
assets[fileType].push(key);
} else {
assets[fileType] = assets[fileType].concat(getAssets(value));
}
});
});
};
var getCurrentAssets = function(){
return assets;
};
getFiles();
return {
getCurrentAssets: getCurrentAssets
};
};
in the controller
var assetmanager = require(config.sroot+'/utils/assetsmanager')(config.sroot,'app');
res.render('layouts/default', {
assets:assetmanager.getCurrentAssets()
});
There is a new version of assetmanager 1.0.0 that I believe accomplishes what you're trying to do more effectively. In the new version you can break apart your assets into groups so that you can support multiple layouts. The github has a complete example here but essentially your asset files ends up looking something like this:
{
"main": {
"css": {
"public/build/css/main.min.css": [
"public/lib/bootstrap/dist/css/bootstrap.css",
"public/css/**/*.css"
]
},
"js": {
"public/build/js/main.min.js": [
"public/lib/angular/angular.js",
"public/js/**/*.js"
]
}
},
"secondary": {
"css": {
"public/build/css/secondary.min.css": [
"public/css/**/*.css"
]
},
"js": {
"public/build/js/secondary.min.js": [
"public/js/**/*.js"
]
}
}
}
And then in your layouts you just include the group you want. Hopefully that helps out.