Unable to call function while using requirejs - javascript

I have been working on a new project for sometime and recently started using require.js in the project.
It all seemed to work fine until I tried making a call from application.js to dashboard.js when the tab #dailyTab or #weeklyTab was clicked or access varialbe var a in dashboard,js. My code is below
main.js
requirejs.config({
baseUrl : '../static/js/',
paths : {
'jquery' : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
'jquery-ui' : 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min',
'bootstrap' : ['//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min', 'bootstrap.min'],
},
shim : {
'bootstrap' : ['jquery'],
'bootswatch' : ['bootstrap'],
}
});
require(["jquery", "jquery-ui", "bootstrap", "dashboard", "application"], function($, jui, bootstrap, dashboard, application) {
$("#myTab a:first").tab("show");
}, function(err) {
console.log(err)
});
dashboard.js
define(function() {
var a = 10;
var Reload = {
dailyCharts : function() {
console.log("Daily Charts");
},
weeklyCharts : function() {
console.log("Weekly Charts");
}
};
var Display = {
none : function(node) {
console.log("none");
},
block : function(node) {
console.log("block");
}
}
});
application.js
define(["jquery", "dashboard"], function(jquery, dashboard) {
$("#dailyTab").click(function() {
dashboard.Reload.dailyCharts();
});
$("#weeklyTab").click(function() {
dashboard.Reload.weeklyCharts();
});
});
Can someone tell me what I have done wrong or what I can do to fix this issue. I accept my coding skills is not very good.
Any help on this is much appreciated.
Thanks in advance

Well, your dashboard.js didn't return anything. How would application.js use it?
define(function() {
var a = 10;
var Reload : {...};
var Display : {...};
//return the interface
return {
Reload : Reload,
Display : Display
}
});

Related

Requirejs lib not a function

I'm trying to use willmcpo/body-scroll-lock on my magento 2 site, but I don't think I'm including the body-scroll-lock lib correctly as it says:
TypeError: disableBodyScroll is not a function
Does anyone know what is the correct way to do this please?
main.js
require([
'jquery',
'bodyScrollLock'
], function ($) {
$(function(){
const
// bodyScrollLock = require('body-scroll-lock');
disableBodyScroll = bodyScrollLock.disableBodyScroll,
enableBodyScroll = bodyScrollLock.enableBodyScroll,
scrollMobileMenu = document.querySelector('.mobile-menu');
disableBodyScroll(scrollMobileMenu);
});
});
requirejs-config.js
var config = {
map: {
"*": {
'bodyScrollLock': 'js/libs/bodyScrollLock'
}
},
deps: [
'bodyScrollLock'
]
};
Figured it out I just needed to include bodyScrollLock here
], function ($, bodyScrollLock) {

Navigate to other controller form app controller

So I have my app controller as always in sapui5:
sap.ui.define(["sap/ui/core/mvc/Controller"], function(Controller) {
"use strict";
return Controller.extend("com.test.controller.App", {
onInit: function() {
if (checkSomething)) {
// here call my first controller
} else {
// here call my second controller
};
}
},
});
});
and I have my second controller which I want to call only if that one if-statement fails
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageBox"], function(Controller, MessageBox) {
"use strict";
return Controller.extend("com.test.Controller1", {
onInit: function() {
this.oRessourceBundle = this.getOwnerComponent().getModel("i18n").getResourceBundle();
}
});
});
here my second controller:
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageBox" ],function(Controller, MessageBox) {
"use strict";
return Controller.extend("com.test.Controller2", {
onInit: function() {
this.oRessourceBundle = this.getOwnerComponent().getModel("i18n").getResourceBundle();
}
});
});
I have a view for both controller so I don't copy it because it is empty so far anyway so there is also a
App.view.xml
Controller1.view.xml
Controller2.view.xml
how do I tell my appcontroller to call different controllers ?
I have also implemented the routes in the manifest.json file
You can call other controller methods like below
sap.ui.controller("com.test.Controller2").yourMethodName();
since my old answer was deleted with some saying "this is not the answer to the question of the author" (while with all respect I was the author and therefore I guess I know if this solved my issue or not) I will explain what is explained in the link I posted:
this is what is in my index.html file:
<script>
sap.ui.getCore().attachInit(function () {
sap.ui.require([
"sap/m/Shell",
"sap/ui/core/ComponentContainer"
], function (Shell, ComponentContainer) {
new Shell({ // placing everything in shell
app: new ComponentContainer({ // component container which holds component file
name: "sap.ui.iyc", // root location of app
height: "100%"
})
}).placeAt("content");
});
});
Component.js This is a file which contains the configuration for router. After configuration and declaring routes and targets we have to initialize() the router in init() function as shown in below code snippet.
sap.ui.define([
"sap/ui/core/UIComponent"
], function (UIComponent) {
"use strict";
return UIComponent.extend("sap.ui.iyc.Component", {
metadata: {
"rootView": "sap.ui.iyc.routepages.App", // initial view
"routing": {
"config": {
"routerClass": "sap.m.routing.Router", // router class
"viewType": "XML", // types of views using in app
"viewPath": "sap.ui.iyc.routepages", // folder of views
"controlId": "app", // container where pages are placed while navigating
"controlAggregation": "pages", // contents which needs to be replced while navigating
"transition": "slide" // navigation transition effect
},
"routes": [{ // defining routes
"pattern": "", // pattern of the URL
"name": "first", // name of route
"target": "first" // name of target
},
{
"pattern": "second",
"name": "second",
"target": "second"
}],
"targets": { // defining targets
"first": { // route name
"viewName": "First" // target view name, will be navigated to this view
},
"second": {
"viewName": "Second"
}
}
}
},
init: function () {
// call the init function of the parent
UIComponent.prototype.init.apply(this, arguments); // calling parent UIComponents
// create the views based on the url/hash
this.getRouter().initialize(); // initializing router
}
});
});
first controller:
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("sap.ui.iyc.routepages.First", {
// getting router which is declared in component file
getRouter : function () {
return sap.ui.core.UIComponent.getRouterFor(this);
},
// this function will trigger when button is clicked
navToSecond : function (oEvent){
this.getRouter().navTo("second"); // calls route name "second"
}
});
});
second controller:
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("sap.ui.iyc.routepages.Second", {
getRouter : function () {
return sap.ui.core.UIComponent.getRouterFor(this);
},
// this function will trigger when button is clicked
navToFirst: function() {
this.getRouter().navTo("first"); // calls route name "first"
}
});
});
for an even better understanding visit the following link:
http://www.inkyourcode.com/how-to-navigate-between-two-views-using-routing/
and of course in your views you will have to implement buttons or whatever you want to trigger those functions which will route you to your views

RequireJS issues while loading and Hamljs

I am using requirejs + jquery + sammy.js + hamljs.
The template engine haml is not working : it runs sammy.haml, but Haml is defined for main.js but not for sammy.haml and cannot run in it. After the page is completely loaded, Haml exists for the console. Why Sammy does not get on well with HAML whereas it should be ?
requirejs.config({
baseUrl: '../../components/',
paths: {
dropkick: 'jquery-dropkick2/jquery.dropkick-1.0.0',
Ladda: 'Ladda/dist/ladda.min',
'jquery-autosize': 'jquery-autosize/jquery.autosize',
mixitup: 'mixitup/jquery.mixitup.min',
jquery: 'jquery/jquery',
sammy: 'sammy/lib/sammy',
'sammy.haml': 'sammy/lib/plugins/sammy.haml',
haml: 'haml/lib/haml',
browser: 'jquery.browser/jquery.browser.min'
},
shim: {
dropkick: {
deps: ['jquery']
},
browser: {
deps: ['jquery']
},
'sammy.haml': {
deps: ['haml']
}
}
});
requirejs(['jquery', 'haml'], function($, Haml) { // They are to be loaded first
requirejs(['sammy', 'sammy.haml', 'browser', 'markdown'], function(sammy, shaml, markdow) { // Then the others
console.log(Haml); // WORK
var app = sammy('#main', function() {
var self = this;
self.use(sammy.Haml);
self.get('/upload', function(context) {
context.app.swap('');
var s = context.render('app/templates/upload.haml', {});
s.appendTo(context.$element())
});
});
});
app.run();
});
});
Finally found the solution ! I defined window.Haml = haml in the main file, and modified sammy.haml.js to get window.Haml function instead of Haml function.

Making Backbone.js modular with Require.js

I am attempting to make my Backbone.js components, models and views modular through Backbone.js. However whenever I attempt to require() one it returns:
function (){return i.apply(this,arguments)}
instead of the Backbone wizardry I require.
I have set up my Require.js like so:
// Configure require.js
require.config(
{
paths: {
"data": "config"
, "jquery": "libs/jquery.min"
, "underscore": "libs/underscore-min"
, "backbone": "libs/backbone-min"
, "events": "collections/events"
, "eventModel": "models/eventModel"
, "eventView": "views/eventView"
}
, shim: {
underscore: {
exports: '_'
}
, jquery: {
exports: '$'
}
, backbone: {
deps: ["underscore"]
, exports: "Backbone"
}
}
}
);
// Initiate app
require(
[
"data"
, "jquery"
, "underscore"
, "backbone"
, "events"
, "eventModel"
, "eventView"
], function(data, $, _, Backbone, Events, EventModel, EventView) {
console.log(Events);
_.each(["data/general.xml"], function(URI) {
var general = new Events({url: URI});
});
}
);
And here is my collections/events.js:
define(
[
"backbone"
, "eventModel"
]
, function(Backbone, EventModel) {
"use strict";
var Events = Backbone.Collection.extend({
model: EventModel
, parse: function(data) {
var parsed = [];
$(data).find('Event').each(function(index) {
parsed.push({
title: $(this).find('title').text(),
date: $(this).find('date').text(),
content: $(this).find('content').text()
});
});
return parsed;
}
, fetch: function(options) {
options = options || {};
options.dataType = "xml";
Backbone.Collection.prototype.fetch.call(this, options);
}
});
return Events;
}
);
I would expect that to return the Events collection, however it clearly isn't. Can anyone see what I am doing wrong?
Everything seems fine. What you see:
function (){return i.apply(this,arguments)}
is the constructor of your class. Pay no attention to it. Instead, try to log new myClass.
Edit:
You don't see any of the methods because they're stored in the prototype of your class. The i function that is called is the "real" constructor (named i because it's been minified).

Backbone router issue

I have a router that does the site navigation nicely and also works when clicking the browsers back / forward button. However, when entering directly an URL I get 404.
Here is my router:
define(function(require) {
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');
var AppRouter = Backbone.Router.extend( {
routes: {
'home' : 'homeHandler',
'webdesign' : 'webHandler',
'mobile' : 'mobileHandler',
'javascript' : 'javascriptHandler',
'hosting' : 'hostingHandler',
'contact' : 'contactHandler'
},
initialize: function() {
this._bindRoutes();
$('.link').click(function(e){
e.preventDefault();
Backbone.history.navigate($(this).attr("href"),true);
});
if(history && history.pushState) {
Backbone.history.start({pushState : true});
console.log("has pushstate");
}
else {
Backbone.history.start();
console.log("no pushstate");
}
console.log("Router init with routes:",this.routes);
},
homeHandler: function(e) {
require(['../views/home-content-view', '../views/home-sidebar-view'],
function(HomeContent, HomeSidebar) {
var homeContent = new HomeContent();
homeContent.render();
var homeSidebar = new HomeSidebar();
homeSidebar.render();
});
},
webHandler: function(e) {
require(['../views/web-content-view', '../views/web-sidebar-view'],
function(WebContent, WebSidebar) {
var webContent = new WebContent();
webContent.render();
var webSidebar = new WebSidebar();
webSidebar.render();
});
},
...
});
return AppRouter;
});
Obviously, I'm missing something.
Any clarification would be greatly appreciated.
Thanks,
Stephan
Backbone operates on a web-page (that has already been loaded in the browser). When you enter a URL in the browser directly, you're making a HTTP-request for that URL to the server. The server is not managed by Backbone. You have to define on the server the behavior when such HTTP-requests are encountered.

Categories

Resources