Backbone with Lodash instead of Underscore, and Browserify - backbone.js

I'm now trying to use Browserify, and I've got a problem with it.
I always use Backbone with Lodash instead of Underscore, so I wrote some shim scripts for Browserify:
shims/lodash.js:
'use strict';
/* global window,require,module */
require('../vendor/lodash.underscore-1.2.0');
module.exports = window._;
shims/backbone.js:
'use strict';
/* global window,require,module */
require('../vendor/backbone-1.0.0');
module.exports = window.Backbone;
app.coffee:
'use strict'
$ = require './shims/jquery'
_ = require './shims/underscore'
Backbone = require './shims/backbone'
I actually use grunt-coffeeify to build the Browserify modules, and it says an error below:
Running "coffeeify:source" (coffeeify) task
Warning: module "underscore" not found from "/Users/User/proj/src/js/vendor/backbone-1.0.0.js" Use --force to continue.
What should I change to work Backbone properly? Thanks in advance.
UPDATE
Somehow, it works with codes below:
shims/lodash.js:
'use strict';
/* global require,module */
module.exports = require('../vendor/lodash-1.2.0');
shims/backbone.js:
'use strict';
/* global window,require,module */
window.$ = require('./jquery');
window._ = require('./lodash');
module.exports = require('../vendor/backbone-1.0.0');
And comment out code below in backbone-1.0.0.js:
//if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
This looks something wrong though...

b is an instance of browserify.
b.require('lodash', {expose: 'underscore'});
for jQuery, look at my version on github : https://github.com/amiorin/jquery

You don't need any shims. All you need is correct alias in browserify task.
alias: ['./node_modules/lodash/dist/lodash.underscore.js:underscore']
Look at my example

Related

Yo meanjs generator - different code style

I am wondering why do I get different code generated from the rest of the mean app. What I mean exactly is this - when I run yo meanjs:angular-config I get a file that looks like this:
(function() {
'use strict';
// My Module module config
angular
.module('my-module')
.run(menuConfig);
menuConfig.$inject = ['Menus'];
function menuConfig(Menus) {
// Config logic
// ...
}
})();
I know that this is ok, but I am interested why don't I get a code block that looks like in the other mean modules, like this:
'use strict';
// Configuring the Articles module
angular.module('users.admin').run(['Menus',
function (Menus) {
Menus.addSubMenuItem('topbar', 'admin', {
title: 'Manage Users',
state: 'admin.users'
});
}
]);
Why is there a difference? I use version 0.4.2 of meanjs.
How can I generate code like in the second code block I posted? I did see some video tutorials where they use the same console command and the same version of meanjs as I do and they get the "expected" code generated.
Are you watching the MEAN Stack Honolulu Challenge by chance? I'm having compatibility issues with MEAN 0.4.2 and that series myself.

Angular - Issue in moving service into separate file

I have a service with a few methods:
function userService($http, API, auth) {
....
}
and then used in my module like:
var app = angular.module('app', ['ngRoute'])
.service('user', userService)
...
All of this is in my app.js file, I want to separate things so its easier to maintain. I'm trying to use the line .service('user', '/services/userService') but its not working any ideas how to i need to reference this?
Thanks.
I think you are creating a new module instead of use yours.
To retrieve an existing module and use it in a separated file, you have to do :
var app = angular.module('app')
.service('user', userService')
// ...
Instead of
var app = angular.module('app', ['ngRoute'])
.service('user', userService')
// ...
Documentation available at https://docs.angularjs.org/guide/module#creation-versus-retrieval
EDIT from #koox00 answer
Don't forgot to load all files related to your module in your markup, in the good order (before load the file containing your module declaration).

Use node_modules inside AngularJS application

I'v just generated an angular application using Yeoman project generator tool. Generated project has a directory "node_modules". Inside this module are a lot of maybe "predefined functions" for array-diff etc.., and i want to use those functions inside my angularJS application(controllers, directives) only if it's possible.
I'v tried to use those node_modules using RequireJS and Node-Browserfy unfortonatelly without any success everytime i got some error . Example "filter is not defiend etc...". Is there any Step by Step tutorial to do this module integration into an AngularJS application?
My project structure is:
This is my bundle.js generated by node-browswerfy
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var myFilter =require('../../node_modules/array-filter/index.js');
},{"../../node_modules/array-filter/index.js":2}],2:[function(require,module,exports){
/**
* Array#filter.
*
* #param {Array} arr
* #param {Function} fn
* #return {Array}
*/
module.exports = function (arr, fn) {
if (arr.filter) return arr.filter(fn);
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (!hasOwn.call(arr, i)) continue;
if (fn(arr[i], i, arr)) ret.push(arr[i]);
}
return ret;
};
var hasOwn = Object.prototype.hasOwnProperty;
},{}]},{},[1]);
This is my controller
'use strict';
/**
* #ngdoc function
* #name alam2App.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the alam2App
*/
angular.module('alam2App')
.controller('MainCtrl', function ($scope) {
var array = [1, 2, 3];
console.log(myFilter (array, function (el, i, arr) {
return false; // I throw it on the ground!
}));
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
Error message i got on console
ReferenceError: myFilter is not defined
Documentation is always a good place to start, requirejs is well documented and their page referencing the use of node and node_modules describes exactly what you need to do.
r.js creates a deployable bundle of all the code you are using and it doesnt much matter which folder you place it in. r.js will bundle all your code into one file, you simple include this in your page and it executes containing all the dependencies you require.
Angular made a poor choice regarding module definition, it wasnt such a terrible choice at the time, just a short-sighted one, so you are stuck with having to shoe-horn in solutions to problems like this. Fortunately the community is fantastic and have come up with multiple solutions. Try searching for ways to combine commonJS modules and AMD modules, or, look for AMD-compliant alternatives to whichever modules you want as dependencies.

Dependencies Between Modules - Controllers?

This tells AngularJS that all values, factories and services defined inside the myUtilModule should be available inside the myOtherModule module too. In other words, myOtherModule depends on myUtilModule.
var myUtilModule = angular.module("myUtilModule", []);
myUtilModule.value ("myValue" , "12345");
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
});
My question is: What if you define controllers inside myUtilModule and try to use them on myOtherModule. Is this possible?
Yes, controllers will also be available between modules, a pratical example could be as follows:
angular.module('test.controllers').controller('HomeCtrl');
and then on your main module:
angular.module('test', [
'test.controllers',
'test.services',
...
];
This helps a lot on unit testing and reusability of packages.

AngularJS: How to have different Services/Controllers in same Module?

I have a Service and a controller in my AngularJS App, that should be in the same module, but are two different files:
// File 1 (Service)
angular.module('myService', ['ngRoute'])
.service('myService', // ...
// File 2 (Controller)
angular.module('myController', ['ngRoute'])
.controller('myController', // ..
This works fine. Now I want to have Service & Controller in one Module so I can load just one instead of two Modules. So I change the first line (of both files) to:
// Change in both files:
angular.module('myModule', ['ngRoute'])
But now I get an error:
Error: [$injector:unpr] ...
Maybe somebody knows, what could be wrong here. Thank you very much!
You can do the following:
var myApp = angular.module('myApp', []);
myApp.controller("myService"
myApp.service("myApp")
Or
angular.module("myModule").controller
angular.module("myModule").service
If you use angular.module('myService', []) twice, you are initializing the same module twice.
If you just use angular.module("myModule"), without the dependencies, you are just calling it.
You have two options -
use a variable as mentioned by Michael
OR
Use it like -
// Initialize myService Module in any JS file
(make sure this file is included before File 1 and File 2
angular.module('myService', ['ngRoute']);
// File 1 (Service)
angular.module('myService').service('myService', // ...
// File 2 (Controller)
angular.module('myService').controller('myController', // ..

Resources