Require JS with parameter - require

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");
});

Related

Cannot Get Typeahead.js Working with MVC 5 Over Remote

I have no idea what I'm doing wrong, but I cannot get typeahead working in my MVC 5 application. I installed everything via NuGet and my view includes #Scripts.Render("~/bundles/typeahead"), which is rendering properly when viewing the source of the view. So the issue isn't that the dependencies are missing.
I am not seeing any drop down appear when I start typing, and using Fiddler I do not see any calls being made out to the remote that I setup that pulls the data.
Here's the line in my view that typeahead is being attached:
#Html.TextBoxFor(m => m.MainInfo.CompanyName,
new { #class = "form-control typeahead", id = "comp-name", autocomplete="off" })
Here's the portion of my script that configures typeahead and bloodhound:
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
Is there something that I've configured wrong in my javascript? I've used a few tutorials as well as their own documentation, but I cannot figure out what I'm doing wrong here. It almost feels like it's not properly initialized, but there are no errors being thrown.
NOTE: Just as an FYI I'm using Bootstrap 3 as well in case that changes anything.
EDIT: Here's my #section Scripts:
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/typeahead")
<script src="#Url.Content("~/Scripts/handlebars.min.js")"></script>
<script src="#Url.Content("~/Scripts/ProjectSetupFormScripts.js")"></script> <-- this is where typeahead is set up
This did the trick for me:
JS
#section Scripts {
<script type="text/javascript">
$(function () {
SetupTipeahead();
});
function SetupTipeahead() {
var engine = new Bloodhound({
remote: {
url: '/Employees/AllEmployees',
ajax: {
type: 'GET'
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FullName);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$('#FullName').typeahead(null, {
displayKey: 'FullName',
source: engine.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<p class="">' + data.FullName + '</p><p class="">' + data.ManNumber + '</p>';
}
}
});
}
</script>
EmployeesController has the following JsonResult
public JsonResult AllEmployees()
{
return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);
}
Hello try to wrap your script in #section scripts {} this will place the script at the bottom just before the </body> tag and make sure you are not calling the function before your bundles load.
#section scripts {
<script>
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
</script>
}

Mismatched anonymous define() in Chrome extension content script

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() {});

Requirejs and nested modules

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

Marionette.Application() has no Method initRegionManager

im struggling with a weird Issue with Backbone.Marionette an requireJS.
RquireJS is configured like https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs says:
require.config({
deps: ['main'],
paths : {
backbone : '../vendor/backbone.marionette/backbone',
underscore : '../vendor/underscore/underscore',
jquery : '../vendor/jquery/jquery',
marionette : '../vendor/backbone.marionette/backbone.marionette.min'
},
shim : {
jquery : {
exports : 'jQuery'
},
underscore : {
exports : '_'
},
backbone : {
deps : ['jquery', 'underscore'],
exports : 'Backbone'
},
marionette : {
deps : ['jquery', 'underscore', 'backbone'],
exports : 'Marionette'
}
}
});
The main.js:
require([
'app'
],
function(App) {
App.start();
}
);
And the app.js:
define([
'marionette'
],
function(Marionette) {
var app = Marionette.Application();
return app;
}
);
But when I wanna start a Application my Console says:
Uncaught TypeError: Object #<Object> has no method '_initRegionManager'
I did nothing special so far:
define(
[
'marionette'
],
function(Marionette) {
"use strict";
var app = Marionette.Application();
// app.on('initialize:after', function() {
// console.log("Initialize:After");
// });
return app;
}
);
And in the main.js (Startingpoint) i require the code above and wanna start it.
But it fails at Marionette.Application();
When i look into the marionette.js i can clearly see underscore extending the Application with the _initRegionManager-Method. Also in the Prototype-list of the Marionette-Object i can see the method.
Any ideas what i'm missing here?
Your require.config ({ … }) should be in main.js and also as Ratweb_on indicated, there should not be “deps: [‘main’]” in the require.config.
You can follow this example in here, and ignore the jquerymobile stuffs. Essentially it dose the initialization in the same way as your code intended.
See main.js and app.js.
Updated
In your app.js
var app = Marionette.Application();
Should be
var app = new Marionette.Application();

RequireJS loading script file but the passed reference is undefined

I've got the following requireJS config. When trying to reference the package/ImagingX module I always get undefined even though I can see that the script has been loaded in firebug. If I move the js file in question into the baseUrl directory and remove package/ it works as expected.
What am I doing wrong?
window.requirejs.config(
{
baseUrl: '/Scripts',
paths: {
"jquery": "./jquery-1.7.1.min",
"jqx": "/Content/Plugins/jqWidgets",
"package" : "/Scripts/packages"
},
urlArgs: "bust=" + (new Date()).getTime(),
shim : {
'jqx/jqxcore': ['jquery'],
'jqx/jqxsplitter': ['jquery','jqx/jqxcore']
}
}
);
window.require(['jquery', 'layoutManager', 'container', 'package/ImagingX'],
function ($,lm,container,px) {
px.Focus();
$(document).ready(function () {
lm.Init(); // Sets up panes
container.Init(); //Set up the containers
});
});
Update 15/10/2012
I'm getting desperate to solve this issue now, I've stripped everything back to the basics so here is the new main file :
(function () {
requirejs.config({
paths: {
"packages": "packages"
}
});
require([
'packages/testmodule'
],
function (tm) {
alert(tm);
});
})();
And the module which is in a sub folder called packages.
define('testmodule',
function () {
alert("called");
return {
set : 'rar '
};
});
I can see the script loaded but it never gets executed, hence I never get a reference for it.
requirejs.config({
paths: {
//"jquery": "./jquery-1.8.2.min",
//"jqx": "/Content/Plugins/jqWidgets",
"templates": 'templates',
"text": "commonRequireJsModules/text",
"domReady": "commonRequireJsModules/domReady",
"packages" : 'packages/'
//'signalR': './jquery.signalR-0.5.3.min',
//'knockout': './knockout-2.1.0',
//'pubsub' : './pubsub'
}
//,urlArgs: "bust=" + (new Date()).getTime()
//,
//shim : {
// 'jqx/jqxcore': ['jquery'],
// 'jqx/jqxsplitter': ['jquery', 'jqx/jqxcore'],
// 'signalR': ['jquery'],
// 'pubsub' : ['jquery']
//}
});
The trailing slash on the packages path seems to have addressed the issue, in part with also removing the name in the define part of the module. So it now looks like
define(['deps'],function(deps){
});
Rather than
define('myMod',['deps'],function(deps){
});
Couple of things:
it seems strange to use window.require instead of just require
names in 'shim' must match names in 'paths', this is not the case, here
document.ready is done for free by require, no need to do it again
So: do you have any loading error in your JS console? Does it says a script is missing?
Here is a working require configuration, Router is in the same folder of this code:
require.config({
paths:{
'jquery':'lib/jquery.min',
'backbone':'lib/backbone.min',
'underscore':'lib/underscore.min',
'router':'Router'
},
shim:{
'backbone':{ deps:['jquery', 'underscore'] },
'router':{ deps:['backbone'] }
}
});
require(['router', 'jquery', 'underscore', 'backbone'],
function (Router) {
var router = new Router();
$('img').hide();
});
});
And the index.html:
<html>
<head>
<script data-main="assets/js/App.js" src="assets/js/lib/require.min.js"></script>
</head>
<body>...</body>
</html>

Resources