ko is not defined Error in Chutzpah - javascript

I'm trying to write Unit Testing for my SPA project. Where we have used the Durandal (Framework), Knockout (Binding) with RequireJs.
I have installed the Chutzpah in Visual Studio 2012.
When i run my Test for the View Model, it throws me below error, even though the knockout js and other js are loaded correctly.
Uncaught ReferenceError: ko is not defined
My Json Config Code:
{
"Framework": "jasmine",
"TestHarnessReferenceMode": "AMD",
"TestHarnessLocationMode": "SettingsFileAdjacent",
"References" : [
{"Path" : "../Scripts/require.js" },
{"Path" : "config.js" }
],
"Tests" : [
{"Path": "tests"}
]
}
My Config Js Code:
require.config({
paths: {
'text': '../Scripts/text',
'durandal': '../Scripts/durandal',
'plugins': '../Scripts/durandal/plugins',
'jquery': '../Scripts/jquery-2.1.4',
'knockout': '../Scripts/knockout-3.3.0'
},
shim: {
}
});
My FirstTest.Js Code:
define(['project/modules/Settings/Subscriber/Viewmodels/Channels'],
function (nChannel) {
describe("Get Channels", function () {
it("will check the Get Channels call and result", function () {
var disp = nChannel.getChannels().then(function () {
var actualResult = ko.toJS(nChannel.Channels);
expect(actualResult.length).toEqual(3);
});
});
});
});
ViewModel Code:
define(['plugins/dialog'], function (dialog) {
var subscriberList = ko.observableArray(); //Getting Error here - while loading the Js for Unit Testing
var JsQ = $; //Getting JQUERY members here. // Works good.
//Other Logics goes here
return {
subscriberList : subscriberList,
JsQ : JsQ
};
});
The Configuration for the Jquery works perfect, since knockout also same as that. But gives error.
Any Idea's / Suggestion why the error?
Do i need to load the ko (knockout) separately?
Edit 1:
I have tried changing the knockout to ko it gives me the error Uncaught Error: Script error for: knockout.
Edit 2:
The problem i'm facing when i apply this solution, those existing code file needs the massive changes and the file counts are in hundreds. From Init.Js we have loaded the Jquery and Knockout. Like below.
requirejs.config({
paths: {
'text': '../Scripts/text',
'durandal': '../Scripts/durandal',
'plugins': '../Scripts/durandal/plugins'
}
});
define('jquery', [], function () {
return jQuery;
});
define('knockout', [], function () {
return ko;
});
So inside any viewmodel we can get the instance of knockout as ko, without declaring the require js stuff in each veiwmodel for the Knockout (As you suggested).
But when i try the same in Chutzpah declaration this is not working. Not sure why.
Hope you understand the problem.

In both modules you show in your question, you use ko but you do not list knockout in your list of dependencies. This is a sure way to get the error you got. Modify your modules to list knockout in the dependencies, and add a corresponding parameter to the callback you give to define. For instance,
define(['knockout', 'plugins/dialog'], function (ko, dialog) {

Related

Value not set to global variable in JS/AngularJs

I am using gulp to run and build to run my application. I am getting file contents using $http service in my index.js file and then setting value of a variable like
window.variablex = "http://localhost:8080/appname".
here is how I am doing it (in index.js)
(function ()
{
'use strict';
angular
.module('main')
.controller('IndexController', IndexController);
function IndexController($http){
$http.get('conf/conf.json').success(function(data){
window.variable = data.urlValue;
}).error(function(error){
console.log(error);
});
}
});
And I've created a factory to call the rest APIs of my backend application like
(function(){
'use strict';
angular
.module('main')
.factory('testService',['$resource',testService]);
function agentService($resource){
var agents = $resource('../controller/',{id:'#id'},
{
getList:{
method:'GET',
url:window.variable+"/controller/index/",
isArray:false
}
});
Now, I except a rest call to made like
http://localhost:8080/appname/controller
But it always sends a call like http://undefined/appname/controller which is not correct.
I can get the new set value anywhere else, but this value is not being set in resource service objects somehow.
I am definitely missing something.
Any help would be much appreciated
As you are using Gulp, I advise you to use gulp-ng-config
For example, you have your config.json:
{
"local": {
"EnvironmentConfig": {
"api": "http://localhost/"
}
},
"production": {
"EnvironmentConfig": {
"api": "https://api.production.com/"
}
}
}
Then, the usage in gulpfile is:
gulp.task('config', function () {
gulp.src('config.json')
.pipe(gulpNgConfig('main.config', {
environment: 'production'
}))
.pipe(gulp.dest('.'))
});
You will have this output:
angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});
And then, you have to add that module in your app.js
angular.module('main', [ 'main.config' ]);
To use that variable you have to inject in your provider:
angular
.module('main')
.factory('testService', ['$resource', 'EnvironmentConfig', testService]);
function agentService($resource, EnvironmentConfig) {
var agents = $resource('../controller/', {id: '#id'},
{
getList: {
method: 'GET',
url: EnvironmentConfig + "/controller/index/",
isArray: false
}
});
}
#Kenji Mukai's answer did work but I may have to change configuration at run time and there it fails. This is how I achieved it (in case anyone having an issue setting variables before application gets boostrap)
These are the sets that I followed
Remove ng-app="appName" from your html file as this is what causing problem. Angular hits this tag and bootstraps your application before anything else. hence application is bootstratped before loading data from server-side (in my case)
Added the following in my main module
var injector = angular.injector(["ng"]);
var http = injector.get("$http");
return http.get("conf/conf.json").then(function(response){
window.appBaseUrl = response.data.gatewayUrl
}).then(function bootstrapApplication() {
angular.element(document).ready(function() {
angular.bootstrap(document, ["yourModuleName"]);
});
});
This will load/set new values everytime you refresh your page. You can change conf.json file even at runtime and refreshing the page will take care of updating the values.

How to load knockout.observableDictionary plugin in requirejs with shim?

This is the plugin
https://github.com/jamesfoster/knockout.observableDictionary
Here is a fiddle showing the problem I am experiencing:
https://jsfiddle.net/L4d84nqc/1/
Code:
requirejs.config({
paths: {
'ko': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min',
'ko.observableDictionary' : 'https://rawgithub.com/jamesfoster/knockout.observableDictionary/master/ko.observableDictionary'
},
shim: {
'ko.observableDictionary' : {
deps: ['ko']
}
}
});
require(['ko', 'ko.observableDictionary'], function(ko) {
console.log(ko);
});
I dont think there is a way to add a property via the require registration (could be wrong?). I would simply add the .js file to the bundle, or in the page, and modify the library js like so...
require(["ko"], function(ko){
(function (ko) {
function DictionaryItem(key, value, dictionary) {
.............. all that yummy code
}
})(ko)
});

RequireJS: How do I pass variables from one file to another?

I'm using require with backbone + backbone-forms. I'm currently using RequireJS to seperate code into multiple files. I have models stored in separate files and want to keep form validators separately.
However, I am unable to access variables defined in one files, in another file that depends on this one. What I get is Uncaught ReferenceError: isEmptyName is not defined. isEmptyName is defined in validators and used in model. Any feedback about RequireJS config is also appreciated.
My config:
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js',
paths: {
jquery: 'lib/jquery',
app: 'lib/app',
wizard: 'lib/jquery.bootstrap.wizard.min',
bootstrap: 'lib/bootstrap.min',
underscore: 'lib/underscore-min',
backbone: 'lib/backbone-min',
backboneForms: 'lib/backbone-forms.min',
langSwitcher: 'lib/lang',
cookie: 'lib/cookie',
datepicker: 'lib/bootstrap-datepicker',
mask: 'lib/jquery.maskedinput.min',
validators: 'modules/validators',
// models
personalData: 'models/personal-data',
addressData: 'models/address-data',
workData: 'models/work-data',
productsData: 'models/products-data',
statmentData: 'models/statment-data',
model: 'models/form',
collection: 'collections/form',
view: 'views/form',
setup: 'setup',
send: 'send',
},
shim: {
'underscore': {
deps: ['jquery'],
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'backbone'
},
// all model needs to go within one collection
'bootstrap' : ['jquery'],
'wizard': ['jquery'],
'backboneForms': ['backbone'],
'validators': ['backbone','mask'],
'personalData' : ['backbone','backboneForms','validators'],
'addressData': ['backbone','backboneForms'],
'workData': ['backbone','backboneForms'],
'statmentData': ['backbone','backboneForms'],
//'collection': ['backbone','backboneForms','personalData'],
//'view': ['backbone','backboneForms','personalData']
}
});
Beginning of validators.js
require(['backbone','backboneForms'], function(){
var lettersOnly = /^[A-Za-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]+$/;
var lettersOnlyDash = /^[A-Za-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ\-]+$/;
var err = {};
var errCh = {};
var errFormat = {};
var isEmptyName = function(value){
err = { message: 'Wpisz imię.'};
if (value.length === 0) return err;
};
Beginning of model.js that needs the validators in validators.js
require(['backbone','backboneForms','mask','validators'], function(backbone,backboneForms,mask,validators){
var PersonalData = Backbone.Model.extend({
schema: {
first_name:{
title: 'Imię',
validators: [isEmptyName, isLetter, minCharCount] //Accessing validators.js members here...
}, ...
I think you're using require when what you really need is define. From When should I use require() and when to use define()?,
With define you register a module in require.js that you than can
depend on in other module definitions or require statements. With
require you "just" load/use a module or javascript file that can be
loaded by require.js.
So here, you have some variables that are defined in one file, but are required to be accessed in another file. Seems like a 'Module', doesn't it? So now, you have two ways of using this file as a module:
Conform to AMD-ness
Conform to chaotic javascript global variable-ness
Using the AMD Approach
validators.js is now a module. Anybody wishing to use 'validator functions' can depend on this module to provide it for them. That is,
define(['backbone','backboneForms'], function(){
var lettersOnly = /^[A-Za-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]+$/;
var isEmptyName = function(value){
err = { message: 'Wpisz imię.'};
if (value.length === 0) return err;
return {
someVariable: lettersOnly,
someFunction: isEmptyName
}
};
You'll notice that the require has been replaced with define. Now, when somebody (model) depends on validator.js, they can access their dependencies as follows
require(['backbone','backboneForms','mask','validators'],
function(backbone, backboneForms, mask, validators) {
var isEmptyNameReference = validators.someFunction;
...
Using shim
Check Requirejs why and when to use shim config, which references this link which says,
if we were to just add the backbone.js file to our project and list
Backbone as a dependency from one of our modules, it wouldn’t work.
RequireJS will load backbone.js, but nothing in backbone.js registers
itself as a module with RequireJS. RequireJS will throw up its hands
and say something like, “Well, I loaded the file, but I didn’t find
any module in there.”
So, you could have your validator.js populate a global Validator namespace, and still use it the way we used it in the example above.
function(){
var lettersOnly = /^[A-Za-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]+$/;
var isEmptyName = function(value){
err = { message: 'Wpisz imię.'};
if (value.length === 0) return err;
Globals.Validator = {
someVariable: lettersOnly,
someFunction: isEmptyName
}
}();
Your config.js would then be,
shim: {
'validator': {
deps: ['backbone','backboneForms'],
exports: 'Globals.Validator'
},
...
Note that you can alias the namespace as you wish, but the alias is just a reference to the existing global object/namespace. This is helpful if you have, say, Foo.Bar.Foobar as your namespace, but want to refer to it as FB. Shimming, hence, is a way for non-AMD libraries to adapt to AMD usage. In this case, option 1 should be sufficient.

method won't trigger when using requireJS

I have some issue with some requireJS setup. I posted a question before but the scope of the latest changed now.
I have some
requirejs.config({
paths: {
'tmpl': 'vendor/upload/tmpl.min'
}
});
require({
paths: {
'videoupload': 'vendor/upload/jquery.ui.videoupload'
}
}, ['js/main_video.js'], function (App) {
App.initial_video_upload();
});
and finally in main_video.js :
define(['tmpl', 'videoupload'], function () {
function initial_video_upload(tmpl, videoupload) {
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
This code works perfectly if I don't use requireJS (loading classically each file). In fact, when this code is triggered, I keep on having a message Uncaught TypeError: Object [object Object] has no method 'tmpl', this method is defined in tmpl.min.js. And this method is invoked in vendor/upload/jquery.ui.videoupload, as so
$.widget('videoupload', {
//...
_renderVideo: function (video) {
this._templateElement().tmpl({
id: video.id,
name: video.title
}).appendTo(this._listElement()).find(
this.options['delete-selector']
);
return this;
},
//...
How can I manage that ? (I had earlier an error time out message for this method tmpl, but it disappeared now, so I don't think this is it)
In the configuration object, the path is not the full path to the JS file BUT the path to the directory containing the JS file, so you may want to do something like this in the main_video.js file:
requirejs.config({
paths:{
'upload': 'vendor/upload'
}
});
define(['upload/tmpl','upload/jquery_videoupload'],function(tmpl, videoupload) {
function initial_video_upload(tmpl,videoupload){
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
And in the main app:
requirejs.config({
paths:{
'js': 'path/to/your/js/folder'
}
});
require(['js/main_video'], function(App) {
App.initial_video_upload();
});
There's a problem in the questions code, so this:
define(['tmpl', 'videoupload'], function () {
should become this:
define(['tmpl', 'videoupload'], function (tmpl, videoupload) {
The first one doesn't expose loaded dependencies to local variables of closure function, so that's might be a problem, although it's not very clear if it's the only one, from the provided code.
I would also like to mention, that it's not a good thing to use multiple requre.js configs, if you're intended to use optimizer. The configs will be overwritten by the last one, so it's a good idea actually to have only one config for the whole project.
Like this:
requirejs.config({
paths: {
'tmpl': 'vendor/upload/tmpl.min',
'videoupload': 'vendor/upload/jquery.ui.videoupload'
}
});

using Backbone JS boilerplate & code navigation

a newbe question:
I've downloaded the backbone boilerplate from https://github.com/david0178418/BackboneJS-AMD-Boilerplate it uses require.js and I wonder about the code navigation during development.
Here is my question:
let's say I have 2 views one extend the other like so:
View 1:
define([
'underscoreLoader',
'backboneLoader',
'text!templates/main.html'
],
function (_, Backbone, MainTemplate) {
"use strict";
return Backbone.View.extend({
template:_.template(MainTemplate),
initialize:function () {
this.render();
},
log:function(msg){
console.log(msg);
},
render:function () {
this.$el.append(this.template({}));
return this;
}
});
}
);
View 2:
define([
'underscoreLoader',
'backboneLoader',
'text!templates/other.html',
'views/main-view'
],
function (_, Backbone, MainTemplate,MainView) {
"use strict";
// how would you navigate to MainView (main-view.js)
return MainView.extend({
template:_.template(MainTemplate),
initialize:function () {
this.render();
},
render:function () {
this.log("my message");
this.$el.append(this.template({}));
return this;
}
});
}
);
Now when I develop (I use IntelliJ) I would like to middle click MainView on the extended view and navigate to the code without having to browse the project tree.
Is that possible using this boilerplate? is there a better approach or a better boilerplate?
I would really like Netbeans's navigator to show me all the methods:
var New_Controller = Backbone.View.extend({
el : null, ...
}
But I can't seem to get it to work. Google came up with something for #lends, but I can't even get Backbone.js to get loaded to the code hint cache.
I ended up installing WebStorm (I saw the IDE in all the egghead.io tutorials) to get the navigator to list all methods and properties.
FYI, Aptana Studio and Zend Studio showed nothing like Netbeans. And Eclipse IDE for JavaScript Web Developers only partially (impractical in real life) works; it flattens the entire hierarchy.
I found this to work fine for me:
the Backbone Objects are wrapped with my custom objects, which allows me to navigate code, extend objects and keep multiple files easily.
Here is how:
Object 1
function ItemModel() {
ItemModel.model = (
Backbone.Model.extend({
initialize:function () {
},
defaults:{
name:"item name"
},
log:function(){
console.log("inherited method");
}
})
);
return new ItemModel.model();
}
Object 2
function ItemModel2() {
ItemModel2.model = (
ItemModel.model.extend({
initialize:function () {
},
defaults:{
name:"item name2"
}
})
);
return new ItemModel2.model();
}
and in my app:
var App = {
item:new ItemModel(),
item2:new ItemModel2()
};

Categories

Resources