require js defining modules in html script tags - requirejs

I am trying to define a module for the initual configuration options of my app inside an script tag in my html. but I get the following error:
Error: Module name "options" has not been loaded yet for context: _. Use require([]) http://requirejs.org/docs/errors.html#notloaded
here is the html:
<script src="Scripts/require.js" data-main="/Recruiter/temp-search/App/main"></script>
<script>
define('options',['jquery'],function($) {
return options = {
salesPhoneNumber : '#ConfigurationManager.AppSettings.Get("SalesPhoneNumber")',
saleInfoMessage : "To access Temp Search candidate details, please call our team on " + salesPhoneNumber,
subscriptionInfo : #Html.Raw(new JavaScriptSerializer().Serialize(Model.AccessInfo ?? null)),
questionProLink: src="#(Request.Url.Scheme)://www.questionpro.com/a/TakeSurvey?id=#(Model.IsRecCon ? AppSettings.SurveyRecConId : AppSettings.SurveyOthersId)&custom1=#Model.RecruiterEmail&custom2=#Model.RecruiterId",
surveyEnabled: '#AppSettings.FlexSurveyEnabled',
whatsNewUrl: '#AppSettings.UrlWhatsNew',
salesPhoneNumber:salesPhoneNumber,
showSaleInfo: '#ViewBag.ShowSaleInfo',
fileDownloadFailCookieName:'#AppSettings.FileDownloadFail',
urls: {
signInUrl: '#string.Format("https://{0}/recruiter/account/signIn", Url.RequestContext.HttpContext.Request.Url.Host)',
signInTempsHome: '/recruiter/temp-search/home',
signInTempsSearch: '/recruiter/temp-search/api/temps',
checkAvailabilityUrl: '/recruiter/temp-search/api/availability',
searchUrl: '/recruiter/temp-search/api/temps/search',
accesslimitUrl: '/recruiter/temp-search/api/ecruiters/accessinfo',
previewUrl: '/recruiter/temp-search/api/temps/preview'
},
elements: {
signInRegisterDialog: $("#signInRegisterDialog"),
noSubscriptionDialog: $("#noSubscriptionDialog"),
searchForm: $("#searchForm"),
searchKeywords: $("#Keywords"),
searchLocation: $("#Location"),
searchRadius: $("#Radius"),
searchSortBy: $("#sortBy"),
searchTemp: $("#Temporary"),
searchContract: $("#Contract"),
searchPayRateFrom: $("#PayRateFrom"),
searchPayRateTo: $("#PayRateTo"),
searchAvailability: $("#AvailabilityConfirmed"),
locationErrorMsg: $("#locationErrorMsg"),
checkAll: $(".checkAll"),
checkCandidate: $(".checkCandidate"),
availability: {
availabilityBtn: $("#availabilityBtn"),
availabilityDialog: $("#availabilityDialog"),
additionalInformation: $("#AdditionalInformation"),
jobPosition: $("#JobPosition"),
jobLocation: $("#JobLocation"),
payRate: $("#JobPayRateFrom"),
payRateTo: $("#JobPayRateTo"),
startOn: $("#StartOnDate"),
duration: $("#Duration"),
checkAvailabilityForm: $("#checkAvailabilityForm"),
availabilityLocation: $("#checkAvailabilityForm #JobLocation"),
candidateIds: $("#CandidateIds"),
tempJobId: $("#TempJobId"),
msgPanel: $("#msgPanel"),
msg: $(".msg"),
errorAvailability: $("#availabilityError"),
availabilityConfirmationDialog: $("#availabilityConfirmationDialog"),
infoBubbleMessage : $("#infoBubbleMessage"),
availabilityConfirmationMsg: $("#availabilityConfirmationDialog .msgDialog"),
downloadInfoLink : $("#downloadInfoLink")
},
preview: {
previewBtn: $('.previewBtn')
},
messagePanel: $("#messagePanel")
},
minWageRate : #Constants.Range.ApprenticeshipsPerHourMin,
authentication : #(Request.IsAuthenticated.ToString().ToLower()),
minDate: '#String.Format("{0:yyyy/MM/dd}", DateTime.Now)',
pageInfo: {
number: #Model.Results.PageNumber,
size: #Model.Results.PageSize,
resultsCount: #Model.TotalResultsCount
},
criteria : #Html.Raw(new JavaScriptSerializer().Serialize(Model.Criteria)),
remainingAccessLimit: #Model.AccessInfo.Remaining,
totalAccessLimit: #Model.AccessInfo.Limit,
availableCandidates: #Model.AvailableCandidates,
candidates: #Html.Raw(new JavaScriptSerializer().Serialize(Model.Results ?? Model.Results.ToJSON()))
};
})
</script>

The problem is not with the code you show in your question but with how you ask RequireJS to load your module. The error message you show happens when you do a require call of this form:
var foo = require('foo');
This kind of require call does not work unless foo is already loaded, and to ensure it is already loaded you can manually load it yourself, or you can have RequireJS do it for you. However, to get RequireJS to do it for you, you need to write your code in a certain way. If you want a module to use foo and you want to use the require above then, you should do:
define(function (require) {
var foo = require('foo');
...
});
Or if you need to use module and exports, the callback can be function (require, exports, module) {....
Also, you should perform the following operations in this order:
Load RequireJS.
Execute define('options', ....
Then and only then start loading your application.
This means removing data-main and using an explicit require call after define('options'.

Related

Unable to add event listener to webNavigation.onCompleted

Using the mock function below along with the dev console:
This call will work:
chrome.webNavigation.onCompleted.addListener(processWebNavChange, filtera);
but when I actually pass in my real var filter it throws this error:
Uncaught TypeError: Could not add listener
My actual data looks like this:
{
url: [ {hostContains: ".im88rmbOwZ"} ]
}
function registerWebNavListener() {
var matchers = getUrlMatchers();
var filter = {
url: matchers
};
// test with mock data filtera that actually works
const filtera = {
url:
[
{hostContains: "example.com"},
]
}
if (matchers.length > 0) {
chrome.webNavigation.onCompleted.addListener(processWebNavChange, filtera);
}
}
async function processWebNavChange(data) {
}
Is there something wrong with my data structure that I'm actually using? I don't believe that the filter object I returned is incorrect
}
EDIT:
I added a new
const filterb = {
url: [ {hostContains: ".im88rmbOwZ"} ]
};
and it still fails with that. The single entry {hostContains: ".im88rmbOwZ"}, was the first item returned from getURLMatchers() which I used as an example of real data being returned.
The above comment on the upper-case letters was the cause of the issue. Converting everything to lowercase resolved the problem.
Although, I am not clear as to why that was a problem to begin with. (If there are any hints in the chromium source code event filter handlers, I'd appreciate it if it could be pointed out).

Grunt variable as filename and file path

I'm trying to use Grunt option to define a file path and file name. This used to work but now I'm getting an unexpected token error.
var myTarget = grunt.option('target');
'build/assets/css/' + myTarget + '.css': 'source/scss/' + myTarget + '/styles.scss'
You should use the special placeholders for variables in file names and strings. First, you should load the option (using grunt.option()) or configuration (using grunt.congif()), as an option for the Grunt initConfig method. Then you should use the special placeholders <%= varname %> to use the loaded options or configurations.
grunt.initConfig({
target : grunt.option('target'),
...
files : {
'build/assets/css/<%= target %>.css' : 'source/scss/<%= target %>/styles.scss'
}
...
});
Configuration can also load an object, so the special placeholder can match object properties too:
grunt.config('definitions', (function() {
return {
target : 'my-target'
};
})());
Later on your config:
grunt.initConfig({
config : grunt.config('definitions'),
...
files : {
'build/assets/css/<%= config.target %>.css' : 'source/scss/<%= config.target %>/styles.scss'
}
...
});
Read more about Grunt option, config and templates in the Grunt official website.
Hope it helps.

GitHub Electron: build menu in required file

I am seasoned in JavaScript, but very new to node and to Electron. I am trying to piece the technique together from code samples and what documentation I can find.
I would like to include my menu code in a separate file. The main code is in a file called renderer.js and the menu code in one called menu.js. A simple example:
// renderer.js
function doit() {
alert('hello');
}
module.exports.doit=doit; // Added
var q=require('./menu');
var q=require('./menu');
// menu.js
var template = [
{
label: 'Test',
submenu: [
{
label: 'Something',
click() {
doit();
}
}
]
}
];
const {remote} = require('electron');
const renderer=require('./renderer'); // Added
const {Menu, MenuItem} = remote;
const app=remote.app; // Addes
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
The menu is created, but when selecting the menu item, I get the message: Uncaught ReferenceError: doit is not defined.
I understand the meaning of the message, and clearly variables are not passed between the files.
How can I accomplish this?
Update: I have added some lines in the sample incorporate the accepted answer below. This now works.
Clearly I did not understand the meaning of require(). It strikes me as odd that each file can require the other. Anyway …
Thanks
If you wish to access symbols defined in one Node module from another you have to export them via module.exports:
// renderer.js
function doit() {
// ...
}
module.exports.doit = doit;
And load the module via require:
// menu.js
const { doit } = require('./renderer');
// OR: const doit = require('./renderer').doit;
var template = [
{
label: 'Test',
submenu: [
{
label: 'Something',
click() {
doit();
}
}
]
}
];
This and much more is covered in the Node API docs.
I am trying to solve the same challenge. Currently I am looking into this:
https://github.com/ragingwind/electron-menu-loader
He basically adds a property 'event' and replaces that with an event handler.

Require, Knockout and pager are Undefined TypeError

I have the following main:
requirejs.config({
paths:{
'text':'../vendor/js/text.min',
'jquery':"../vendor/js/jquery.min",
'boostrap':"../vendor/js/bootstrap.min",
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
'pager':"../vendor/js/pager",
'imageGroupsVm':'../js/viewModels/imageGroupsViewModel',
'panelVm':'../js/viewModels/panelViewModel',
'compMessage':'../js/components/message',
'extBooleanToggle':'../js/extenders/booleanToggle'
},
shim:{
'bootstrap':['jquery'],
'pager':['ko'],
},
waitSeconds: 200,
});
define(['jquery','ko','pager','panelVm'],function($,ko,pager,panelVm)
{
pager.extendWithPage(panelVm);
ko.applyBindings(panelVm);
pager.start();
});
But for some reason I get these 2 error messages:
TypeError: ko is undefined
Stack trace:
pagerJsModule#http://localhost/symphotest/assets/vendor/js/pager.js:150:9
#http://localhost/symphotest/assets/vendor/js/pager.js:1506:20
newContext/context.execCb#http://localhost/symphotest/assets/vendor/js/require.min.js:1690:24
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:865:43
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable#http://localhost/symphotest/assets/vendor/js/require.min.js:1177:17
newContext/Module.prototype.init#http://localhost/symphotest/assets/vendor/js/require.min.js:783:21
callGetModule#http://localhost/symphotest/assets/vendor/js/require.min.js:1204:17
newContext/context.completeLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1604:1
newContext/context.onScriptLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1711:21
require.min.js:900:37
TypeError: pager is undefined
Stack trace:
#http://localhost/symphotest/assets/js/panel-main.js:65:5
newContext/context.execCb#http://localhost/symphotest/assets/vendor/js/require.min.js:1690:24
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:865:43
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable/</<#http://localhost/symphotest/assets/vendor/js/require.min.js:1140:29
bind/<#http://localhost/symphotest/assets/vendor/js/require.min.js:131:20
newContext/Module.prototype.emit/<#http://localhost/symphotest/assets/vendor/js/require.min.js:1190:21
each#http://localhost/symphotest/assets/vendor/js/require.min.js:56:31
newContext/Module.prototype.emit#http://localhost/symphotest/assets/vendor/js/require.min.js:1189:17
newContext/Module.prototype.check#http://localhost/symphotest/assets/vendor/js/require.min.js:940:25
newContext/Module.prototype.enable#http://localhost/symphotest/assets/vendor/js/require.min.js:1177:17
newContext/Module.prototype.init#http://localhost/symphotest/assets/vendor/js/require.min.js:783:21
callGetModule#http://localhost/symphotest/assets/vendor/js/require.min.js:1204:17
newContext/context.completeLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1604:1
newContext/context.onScriptLoad#http://localhost/symphotest/assets/vendor/js/require.min.js:1711:21
require.min.js:900:37
Furtermore The panelViewModel.js contains:
define(['ko','imageGroupsVm','compMessage'],function(ko,ImageGroupsVM,loginViewModel)
{
var image_groups=new ImageGroupsVM();
return {'imageGroups':image_groups};
});
And the ImageGroupsViewModel Contains:
define(['ko','jquery'],function(ko,$)
{
console.log(ko);
return function imageGroupsViewModel()
{
var self=this;
self.albums=ko.observableArray();
self.init=function()
{
self.albums([]);
self.fetchData();
}
self.fetchData=function()
{
console.log("Data Fetched");
};
function Album(data)
{
}
};
})
All the JS files that I have are: (note that tin vendor classes are the external libraries I load)
I managed to fix it by replacing the 'ko' with 'knockout' whenever is required.
More specifically on main (the file you include in data-main on your html)
The following line:
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
Changed into:
'knockout':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
I Included on shim:
'pager':['knockout'],
And the
define(['jquery','ko','pager','panelVm'],function($,ko,pager,panelVm)
Changed into
define(['jquery','knockout','pager','panelVm'],function($,ko,pager,panelVm)
Therefore my main is:
requirejs.config({
paths:{
'text':'../vendor/js/text.min',
'knockout':"https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min",
'pager':"../vendor/js/pager.min",
'jquery':"../vendor/js/jquery.min",
'boostrap':"../vendor/js/bootstrap.min",
'imageGroupsVm':'../js/viewModels/imageGroupsViewModel',
'panelVm':'../js/viewModels/panelViewModel',
'compMessage':'../js/components/message',
'extBooleanToggle':'../js/extenders/booleanToggle'
},
shim:{
'pager':['knockout'],
'bootstrap':['jquery'],
},
waitSeconds: 200,
});
define(['jquery','knockout','pager','panelVm'],function($,ko,pager,panelVm)
{
pager.extendWithPage(panelVm);
ko.applyBindings(panelVm);
pager.start();
});
Also on my other javascript files on my project that are loaded with require I changed the line:
define(['ko',...,'other_lib'],function(ko,....,other_lib)
With:
define(['knockout',...,'other_lib'],function(ko,....,other_lib)
Note:
I also changed theese lines on other main.js that I load with require on another pages:
'ko':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
Changed into:
'knockout':"http://knockoutjs.com/downloads/knockout-3.4.0.debug",
I did this in order to load all the modules I make by using require.

Orchard CMS Contrib.Review module

I am beginner in Orchard CMS and i need add voting functionality to content. I have installed Contib.Vote and Contrib.Review modules. After that i have added Review part to page content type. Also, i have executed recipe. At the first look everything is fine, but link for review refer to the same page with # symbol and nothing is happenning by clicking on it. It seems like module does not work or work incorrectly. Please help with my problem.
UPD.
Hi devqon and thanx for your help. Your answer was really useful for me. According to your advice i was looking around javascript inside Review Part view file (Parts_Reviews.cshtml). Just for a test i changed its source code a little bit.
#using (Script.Foot())
{
<script type="text/javascript">
//<![CDATA[
(function () {
var numberOfReviewsToShowByDefault = 5;
var $showAllReviewsLink = $('#showAllReviewsLink');
var $deleteReviewConfirmationDialogDiv = $('#deleteReviewConfirmationDialogDiv');
$deleteReviewConfirmationDialogDiv.dialog({ autoOpen: false, modal: true, resizable: false });
$('#deleteReviewLink').click(function () {
$('#reviewId').val($(this).attr("data-review-id"));
ShowDeleteReviewDialog();
return false;
});
$('#showReviewFormLink').click(function () {
$('#createReviewLinkDiv').slideToggle('fast', function () { $('#reviewFormDiv').slideToggle('fast'); });
return false;
});
$('#cancelCreateReviewLink').click(function () {
$('#reviewFormDiv').slideToggle('fast', function() { $('#createReviewLinkDiv').slideToggle('fast'); });
return false;
});
$('#deleteReviewForm').submit(function () {
$('input[type=submit]', this).attr('disabled', 'disabled');
});
$('#cancelDeleteReviewButton').click(function () {
CloseConfirmationDialogDiv();
return false;
});
var rowCount = $('#reviewsList li').length;
if (rowCount > numberOfReviewsToShowByDefault) {
SetupToggle();
}
if (document.location.hash === '#Reviews') {
var topPx = $('#reviews-heading').position().top;
$('body,html').animate({ scrollTop: topPx }, 'slow');
}
if ($("#comment").length) {
var characterCountUpdater = new CharacterCountUpdater($("#comment"), $("#commentCharactersLeft"));
setInterval(function() { characterCountUpdater.UpdateCharacterCount(); }, 100);
$("#comment").keypress(function() { characterCountUpdater.UpdateCharacterCount(); });
if ($("#comment").val().length) {
$("#showReviewFormLink").trigger("click");
}
}
function CharacterCountUpdater(commentBox, charactersLeftBox)
{
this.commentBox = commentBox;
this.charactersLeftBox = charactersLeftBox;
this.maxLength = commentBox.attr("maxlength");
commentBox.removeAttr("maxlength");
return this;
}
Now form for review is displayed. The form looks good, submit button works, character counter works too. But i still can't apply my rating. Stars not react on clicking. That is why submit operation ends with error 'In order to submit a review, you must also submit a rating.'. Look like something inside Parts.Stars.NoAverage.cshtml does not work. Please, help me.
According to the project's site it is a known issue: broken from version 1.7.2.
When looking at the code of the Parts_Reviews.cshtml it says the following on lines 20-24:
string showReviewUri = "#";
if (!Request.IsAuthenticated)
{
showReviewUri = Url.Action("LogOn", "Account", new { area = "Orchard.Users", ReturnUrl = Context.Request.RawUrl });
}
and on line 29:
<div id="createReviewLinkDiv"><span id="createReviewLinkSpan">#noReviewsYetText<a id="showReviewFormLink" href="#showReviewUri">#reviewLinkText</a></span></div>
Therefore, it was intended to let the anchor be # when the request is authenticated (you are logged on). This means it probably will be handled in JavaScript, which can be seen on lines 105-112:
$('#showReviewFormLink').click(function () {
$('#createReviewLinkDiv').slideToggle('fast', function () { $('#reviewFormDiv').slideToggle('fast'); });
return false;
});
$('#cancelCreateReviewLink').click(function () {
$('#reviewFormDiv').slideToggle('fast', function() { $('#createReviewLinkDiv').slideToggle('fast'); });
return false;
});
This piece of code should let you see the form to write a review, so something is going wrong there presumably. When there's something wrong in this jQuery code it probably gives an error in the console, so check out the browser's console when you click the 'Be the first to write a review' link.
This should get you further, if you don't know what to do please provide the error and I will try to dig more. I haven't downloaded the module so I don't have live feed.
Console of Firefox tells: $(...).live is not a function. It refers to Contrib.Stars.js source code file. This function is not supported in jquery now and i replaced it by .on() function in all places api.jquery.com/on. Now module works fine.
Check out my comment at the site below to see how I was was able to get it working again on Orchard 1.8.1:
Orchard Reviews Project Site
You basically just need to change 3 different lines in the Contrib.Stars.js file but I would recommend copying the .js file along with the Review module's different views to a custom theme directory, in order to override everything and force the Reviews module to use your edited .js file:
On line 12 & 13:
Change this:
$(".stars-clear").live(
"click",
To this:
$("body").on(
"click", ".stars-clear",
On line 44 & 45:
Change this:
.live(
"mouseenter",
To this:
.mouseenter(
On line 48 & 49:
Change this:
.live(
"mouseleave",
To this:
.mouseleave(

Resources