Controller isn't counted as a function - javascript

I have many different controllers throughout this project and all of them are declared the same way. This one now isn't getting called/giving an error and I have no clue why. I've looked through it and it all looks right to me.
I think it's probably some syntax error I'm not seeing. If its something else please tell me. I'm trying to learn angular and everything helps. Also if you need anything else just tell me.
I've made sure its not that the app.js name got changed and been looking for missing syntax but can't find anything.
https://docs.angularjs.org/error/ng/areq?p0=companyDepartmentController&p1=not%20a%20function,%20got%20undefined
company-department-controller.js
app.controller('companyDepartmentController', ['$scope', '$timeout', 'companyService', function ($scope, $timeout, companyService) {
/**
* Create/Manage Company Departments & Shifts
*
*/
// INITIALIZE VARIABLES *********************************************************************************
var vm = this;
vm.Departments = [];
vm.activeDepartment = {}
vm.departmentBeforeEdit = {};
vm.activeShift = {};
vm.OffsetString = "";
vm.SaveDepartmentSuccessMessage = null;
vm.SaveDepartmentErrorMessage = null;
// STARTUP **********************************************************************************************
(vm.GetDepartments = function () {
companyService.GetDepartmentsWithShiftInformation().success(function (data) {
console.log('hi');
for (i = 0; i < data.length; i++) {
console.log(data[i])
}
vm.Departments = data;
// for now we are limiting this to 1
vm.activeDepartment = vm.Departments[0];
vm.setTimeZoneOffsets(vm.activeDepartment);
});
})();
// move to global location? handle this better?
(vm.findLocalOffsetString = function () {
console.log('hi1');
vm.OffsetString = moment(new Date()).format('ZZ');
})();
// $BROADCAST/$ON EVENTS ********************************************************************************
// EVENTS ***********************************************************************************************
vm.saveDepartment = function (department) {
// new
if (department.DepartmentID === 0 || typeof department.DepartmentID === 'undefined') {
}
// update
else {
companyService.UpdateDepartmentHeader(department).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
department.InEdit = false
});
}
};
vm.editDepartment = function (department) {
vm.activeDepartment = department;
vm.departmentBeforeEdit = angular.copy(vm.activeDepartment);
vm.activeDepartment.InEdit = true;
};
vm.cancelDepartmentEdit = function (department) {
for (var i = 0; i < vm.Departments.length; i++) {
if (department.DepartmentID === vm.Departments[i].DepartmentID) {
vm.Departments[i] = vm.departmentBeforeEdit;
vm.departmentBeforeEdit = {};
vm.activeDepartment = vm.Departments[i];
break;
};
};
};
vm.addShift = function () {
if (!vm.activeDepartment) return;
vm.activeShift = {
DepartmentID: vm.activeDepartment.DepartmentID,
StartTime: new Date(),
LocalStartTime: new Date(new Date() + vm.OffsetString)
};
vm.activeShift.StartTime.setSeconds(0);
vm.activeShift.LocalStartTime.setSeconds(0);
};
vm.deleteShift = function (shift) {
if (!shift) return;
if (confirm("Are you sure you want to delete the shift: " + shift.Name + "?")) {
companyService.DeleteShift(shift).success(function () {
angular.forEach(vm.activeDepartment.Shifts, function (c, i) {
if (c.ShiftID === shift.ShiftID) {
vm.activeDepartment.Shifts.splice(i, 1);
};
});
});
};
};
vm.setTimeZoneOffsets = function (department) {
if (!department || !department.Shifts || department.Shifts.length === 0) return;
for (var i = 0; i < department.Shifts.length; i++) {
department.Shifts[i].LocalStartTime = new Date(department.Shifts[i].StartTime + vm.OffsetString);
department.Shifts[i].EndTime = moment(department.Shifts[i].StartTime).add(department.Shifts[i].Duration, 'hours').toDate()
};
};
var fixTimezoneOnSave = function (shift) {
shift.StartTime = new Date(shift.LocalStartTime).toLocaleString();
};
vm.setActiveShift = function (shift) {
if (!shift) return;
vm.activeShift = angular.copy(shift);
};
vm.saveShift = function (shift) {
fixTimezoneOnSave(shift);
// new shift
if (shift.ShiftID === 0 || typeof shift.ShiftID === 'undefined') {
companyService.AddShift(shift).success(function (data) {
shift.ShiftID = data;
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
// updating existing
else {
companyService.UpdateShift(shift).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
}
var getUpdatedShiftsAndInfo = function () {
companyService.DepartmentAndShiftInformation(vm.activeDepartment.DepartmentID).success(function (data) {
vm.activeDepartment.DepartmentShiftInformation = data.DepartmentShiftInformation;
vm.activeDepartment.Shifts = data.Shifts;
vm.setTimeZoneOffsets(vm.activeDepartment);
});
};
var resetDepartmentMessage = function () {
// clear error/success message if they have values still
if (vm.SaveDepartmentSuccessMessage != null) {
$timeout(function () { vm.SaveDepartmentSuccessMessage = null; }, 2000);
}
if (vm.SaveDepartmentErrorMessage != null) {
$timeout(function () { vm.SaveDepartmentErrorMessage = null; }, 2000);
}
};
// create controller object in console if we have logging turned on
if (spectrum.LoggingEnabled) {
spectrum.logController(vm);
};
}]);
_CompanyDepartment.cshtml
<div class="container-fluid" data-ng-controller="companyDepartmentController as cd">
</div>
#section scripts {
#Scripts.Render("~/bundles/companyDepartments")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/angularjs")
}
app.js
var app = angular.module('app', ['angularFileUpload', 'ngSanitize', 'ui.mask', 'ui.select', 'ui.bootstrap', 'ui.bootstrap.tpls', 'angular.filter', 'smart-table', 'colorpicker.module'])
.config(function ($httpProvider) {
//make delete type json to facilitate passing object
//to our generic method.
$httpProvider.defaults.headers["delete"] = {
'Content-Type': 'application/json;charset=utf-8'
};
});

Outside of a naming issue with the controller(which I can't see), I would imagine your issue dealing with the company-department-controller.js not being loaded.
In setting up your angular project, I would suggest that you follow this angular styleguide. It has been very helpful to me in creating a well structured project.

Related

share objects between controllers using services [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 5 years ago.
I have to controllers the first controller is "cockpitController"and the other one "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .
PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).
Le service idCardSupplierWarnService :
var app = angular.module('idCardSupplierWarn');
app.service('idCardSupplierWarnService', function () {
this.idRefNum = "";
this.idSupNum = "";
this.codeSuppNum = "";
this.setParam = function (paramSet) {
console.log(paramSet);
this.idRefNum = paramSet.designRefPart;
this.idSupNum = paramSet.idSuppNumber;
this.codeSuppNum = paramSet.codeSupp;
};
this.getParamSupNum = function () {
return this.idSupNum;
};
this.getParamCodeSupNum = function () {
return this.codeSuppNum;
};
this.getParamIdRefNum = function () {
return this.idRefNum;
};
});
Le controller cockpitController :
(function () {
angular
.module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
.controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {
var urlSuppliersWarning = 'rest/suppliers/warnings';
var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';
var self = this;
serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
self.suppliersWarning = results[0].data;
});
this.change = function () {
if (this.openWindow) {
this.openWindow = false;
}
else {
this.openWindow = true;
}
};
$scope.openNewWindowRef = function (url, params) {
console.log(params);
idCardSupplierWarnService.setParam(params);
console.log(idCardSupplierWarnService.getParams());
$window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
};
$scope.openNewWindowSupp = function (url, params) {
idCardSupplierWarnService.setParam(params);
console.log(idCardSupplierWarnService);
$window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
};
this.process = function (items) {
if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {
serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
self.suppliersWarningDetails = results[0].data;
});
}
serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
self.suppliersWarning = results[0].data;
});
}
}]);
})();
Le controller **idCardSupplierWarnController :**
(function () {
angular
.module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
.controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {
var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';
var self = this;
var params = {} ;
params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
params.idSupNum = idCardSupplierWarnService.getParamSupNum();
params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
console.log(params.codeSuppNum);
serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
self.suppliersWarningsList = results[0].data;
});
}]);
})();
"This" in the functions of your service refers to the individual functions in your service, not the service itself.
Modify your service to look like this:
app.service('idCardSupplierWarnService', function () {
var service = this
service.idRefNum = "";
service.idSupNum = "";
service.codeSuppNum = "";
service.setParam = function (paramSet) {
console.log(paramSet);
service.idRefNum = paramSet.designRefPart;
service.idSupNum = paramSet.idSuppNumber;
service.codeSuppNum = paramSet.codeSupp;
};
service.getParamSupNum = function () {
return service.idSupNum;
};
service.getParamCodeSupNum = function () {
return service.codeSuppNum;
};
service.getParamIdRefNum = function () {
service this.idRefNum;
};
return service
});
You need to inject idCardSupplierWarn module into cockpit module, to access the service.
angular.module("cockpit", ['mm.foundation', 'security', 'message', `isteven-multi-select`, `idCardSupplierWarn`])

JavaScript plugin false positives for function complexity and function length

We are constantly getting false positive issues from our JavaScript plugins regarding the function complexity and function length rules.
The reason is that we have functions that are written inside function and the outer functions get the issues.
I understand that technically the complexity looks at everything,
but isn't there a way of getting the plugin to look only at the functions themselves?
(other than marking it as false positive)
Server version 4.5.6
JavaScript plugin version 2.9
There is a complexity issue of rule "javascript:FunctionComplexity" (complexity=25) for the redeployCtrl function.
This is the code, as you can see the actual complexity is from the inner functions.
is there a way around this other than marking the issue as false positive (and losing the complexity issue for the inner functions) or writing a custom rule?
thanks.
function redeployCtrl($scope, utilService, $filter, $location, generalSettings, $uibModalInstance, $uibModal, $timeout,scheme) {
$scope.openStart = openStart;
$scope.isSubmitable = isSubmitable;
$scope.ipCheckbox = ipCheckbox;
$scope.deploy = deploy;
$scope.init = init;
$scope.cancel = cancel;
function init() {
$scope.scheme = scheme;
$scope.loading = 'false';
$scope.envSchemes = [];
$scope.isPermanent = false;
$scope.permanent = {};
$scope.scheme.Scheme.Description = null;
$scope.scheme.Scheme.ExpTime = null;
var max = generalSettings.CalendarEndDate;
$scope.maxDate = new Date();
$scope.maxDate.setMonth($scope.maxDate.getMonth() + max);
$scope.minDate = new Date();
$scope.minDate = $scope.minDate.setDate($scope.minDate.getDate() + generalSettings.MinExpirationDate);
$scope.dateOptions = {
'year-format': 'yyyy',
'starting-day': 1
};
utilService.post(generalSettings.serverPath + 'envscheme/ListSupervisors/', { })
.then(function (data) {
$scope.supervisors = data;
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to retrieve data", "img_error");
});
utilService.post(generalSettings.serverPath + 'envscheme/ListPermReasons/', { })
.then(function (data) {
$scope.permReasons = data;
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to retrieve data", "img_error");
});
}
function openStart() {
$timeout(function () {
$scope.startOpened = true;
});
}
function deploy(scheme, isPermanent) {
if (isPermanent) {
scheme.Scheme.ExpTime = '01/01/9999';
scheme.Scheme.ApprovedBy = $scope.permanent.approvedBy;
if ($scope.permanent.mainReason === 'Other') {
scheme.Scheme.Reason = $scope.permanent.customReason;
} else {
scheme.Scheme.Reason = $scope.permanent.mainReason;
}
} else {
$scope.scheme.Scheme.ExpTime = utilService.getFormattedDate($scope.scheme.Scheme.ExpTime);
}
$scope.loading = 'true';
utilService.post(generalSettings.serverPath + 'envscheme/ReCreateEnv', scheme)
.then(function (data) {
if (data.Success) {
utilService.alertAmpm("Deploy started successfuly", "Info", "img_information");
$location.path("/MyEnvironments");
}
else {
utilService.alertAmpm(data.Reason, "Failed to Re-Deploy", "img_error");
$scope.loading = 'false';
}
if (data.Reason.indexOf("Session was not found") < -1) {
sessionStorage.clear();
$scope.loading = 'false';
}
}).catch(function (data) {
utilService.setError(data.ExceptionMessage, "Failed to Re-Deploy", "img_error");
$scope.loading = 'false';
});
}
function isSubmitable(invalid, modules) {
if (!invalid) {
for (var i = 0; i < modules.length; i++) {
if (modules[i].ipchkBox) {
if (!modules[i].OS.Parameters.IP) {
return true;
}
}
}
return false;
}
return true;
}
function ipCheckbox(checkBox, name) {
if (!checkBox) {
var name1 = "ipText" + name;
$('[name=' + name1 + ']').val('');
$scope.scheme.Scheme.modules[name].OS.Parameters = new Object();
}
}
function cancel() {
$uibModalInstance.dismiss('cancel');
}
Roy.
These rules force the coding with less nested functions. They ignore some cases like IIFE or practices accepted in some frameworks (AMD, Angular). But that's obviously is not your case.
So if you think that this coding practice is not for you, the only thing you can do is to disable the rules (and may create custom rules counting only lines you want).

Angular filter with typescript is not working after minification

I wrote an angular filter with typescript which works fine until I minify the source code.
Here is the filter:
module App.Test {
export interface IGroupingFilter extends ng.IFilterService {
(name:"grouping-filter"): (collection:any[]) => collection:any[];
}
class GroupingFilter {
static $inject:string[] = ["underscore"];
static ConvertDateTime(item:any):number {
var time = "" + item.time;
var newTime = (time.length == 3) ? "0" + time : time;
return +(item.pickupDate.replace(/\-/g, '') + newTime);
}
public static Factory(underscore:UnderscoreStatic) {
return underscore.memoize((collection:any[]) => {
var groupKey = "id";
var group:any = underscore.groupBy(collection, (item:any) => {
return item[groupKey];
});
var grpArray = [];
angular.forEach(group, (item) => {
grpArray.push({
"groupKey": item[0][groupKey],
"items": item
});
});
var grpArraySorted = underscore.sortBy(grpArray, (grpObj:any) => {
var min:any = underscore.min(grpObj.items, (item:any) => {
return GroupingFilter.ConvertDateTime(item);
});
return GroupingFilter.ConvertDateTime(min);
});
return grpArraySorted;
});
}
}
angular.module("app").filter("groupingFilter", GroupingFilter.Factory);
}
Here is the minified version:
var App;
!function (t) {
var e;
!function (t) {
var e = function () {
function t() {
}
return t.ConvertDateTime = function (t) {
var e = "" + t.time, r = 3 == e.length ? "0" + e : e;
return +(t.pickupDate.replace(/\-/g, "") + r)
}, t.Factory = function (e) {
return e.memoize(function (r) {
var n = "id", i = e.groupBy(r, function (t) {
return t[n]
}), o = [];
angular.forEach(i, function (t) {
o.push({groupKey: t[0][n], items: t})
});
var a = e.sortBy(o, function (r) {
var n = e.min(r.items, function (e) {
return t.ConvertDateTime(e)
});
return t.ConvertDateTime(n)
});
return a
})
}, t.$inject = ["underscore"], t
}();
angular.module("app").filter("groupingFilter", e.Factory)
}(e = t.Test || (t.Test = {}))
}(App || (App = {}));
Here is the angular error message
Error: [$injector:unpr] Unknown provider: eProvider <- e <-
groupingFilterFilter
Many thanks
The reason it does not work when minified is that you inject "underscore" into the FooFilter class not the actual filter, which is the result of FooFilter.Factory. To create such a simple filter you don't really need a class, just pass a simple function.
angular.module('app').filter('fooFilter', fooFilter);
fooFilter.$inject = ['underscore'];
function fooFilter(underscore) {
return underscore.memoize((collection:any[]) => {
return underscore.shuffle(collection);
});
}
If you really want to write the filter factory function as a static class method, you could use the array syntax like this:
angular.module("app")
.filter("groupingFilter", ['underscore', GroupingFilter.Factory]);
Remove the $inject array from your class in this case.

AngularJS share function/common code in a controller

I have a subroutine I want to use in my controller. In the case or working with data, a new record blanks fields, as would a screen clear, and after some other processes, I would like to clear the editable fields on the view.
Controller:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
function ClearMemberStruture()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);
ClearMemberStructure() is used to reset the common structure fields and the Edit flag which controls showing information on the screen. When I run this code, I always get a
ReferenceError: ClearMemberStructure is not defined
How can I share this common function in my controller in AngularJS?
If I add a Factory, I can achieve this using calls to the factory:
angular.module('MyApp').factory("MemberRecord", function() {
var Member = {
Key: "",
Name: "",
Points: ""
};
return {
Clear: function() {
Member.Key = "";
Member.Name = "";
Member.Points = "";
return Member;
}
};
}
);
And then in the controller:
$scope.member = MemberRecord.Clear();
Is there a way to do the simply function style code sharing, as I do want this to be handled as a private function, but cannot get it to recognize the function in the controller.
var ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
is your solution to declare ClearMemberStruture without breaking your whole code.
I use a separate file with factories to share code between controllers.
App.factory('CommonServices', function ($http) {
return {
createComment: function($api_key, $post_id, $comment) {
var comment_data = {
content: $comment
};
return $http({
url: '/api/v1/posts/' + $post_id + '/comments',
method: "POST",
headers: { 'X-API-TOKEN': $api_key },
params: comment_data,
data: ''
})
}
});
Then in a controller you can access the common functions like:
$scope.saveComment = function($post_id) {
CommonServices.createComment($scope.api_key, $post_id, $scope.comment.text)
.then(function(_data) {
var index = $scope.feed_items.filter(function (post) { return post.id == $post_id });
index[0].comments.unshift(_data.data);
$scope.showComment = false;
});
}
I prefer to use factory for Member and encapsulate method there. But you can try the easier way:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
var that = this;
that.ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
that.ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);

Communication between Stores in Reactjs

I develop an application which based on Reactjs and Flux. There is a problem of communication between Stores: ProjectsStore and TasksStore.
In the method getAllForCurrentProject of TasksStore, I call ProjectsStore.getCurrentId(). I get an Uncaught TypeError: undefined is not a function as a result. The typeof ProjectsStore is object in getAllForCurrentProject. When I call ProjectsStore.getCurrentId() from any component it works fine.
What is the reason for this behavior?
In the example MessageStore asks ThreadStore with the same pattern:
getAllForCurrentThread: function() {
return this.getAllForThread(ThreadStore.getCurrentID());
}
My stores:
ProjectsStore.js:
'use strict';
var Dispatcher = require('../dispatcher/Dispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var _ = require('underscore');
var Api = require('../services/Api');
var ProjectsConstants = require('../constants/ProjectsConstants');
var TasksStore = require('../stores/TasksStore');
var changeEvent = 'projectsChanged';
var current = 0;
var items = [];
function requestItems() {
return Api.Projects.getAll();
}
function setItems(data) {
items = data;
}
var ProjectsStore = assign({}, EventEmitter.prototype, {
emitChange: function () {
this.emit(changeEvent);
},
getAll: function () {
return items;
},
getCurrentId: function() {
return current;
},
getCurrent: function() {
var item = _.where(items, { id: this.getCurrentId() });
return (typeof item[0] == 'object' ? item[0] : null);
},
getChildrenOf: function(id, isInclude) {
var result = (typeof isInclude == 'boolean' && isInclude === true ? [id] : []),
children = _.chain(items).where({ parent: id }).pluck('id').value();
result.concat(children);
return result;
}
});
ProjectsStore.dispatchToken = Dispatcher.register(function (payload) {
var action = payload.action;
switch (action.type) {
case ProjectsConstants.projectsSetCurrent:
current = action.data;
break;
case ProjectsConstants.projectsGetAll:
requestItems();
break;
case ProjectsConstants.projectsGetAllSuccess:
setItems(action.data);
break;
default:
return true;
}
ProjectsStore.emitChange();
return true;
});
module.exports = ProjectsStore;
TasksStore.js:
'use strict';
var Dispatcher = require('../dispatcher/Dispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var _ = require('underscore');
var Api = require('../services/Api');
var TasksConstants = require('../constants/TasksConstants');
var ProjectsStore = require('../stores/ProjectsStore');
var changeEvent = 'tasksChanged';
var items = [];
function requestItems() {
return Api.Tasks.getAll();
}
function setItems(data) {
items = data;
}
var TasksStore = assign({}, EventEmitter.prototype, {
emitChange: function () {
this.emit(changeEvent);
},
getAll: function () {
return items;
},
getAllForProject: function(id) {
var projects = ProjectsStore.getChildrenOf(id, true);
return _.chain(items).where({ parent: projects });
},
getAllForCurrentProject: function() {
console.log('Type:', typeof ProjectsStore); // <-- object
console.log('Inspect:', ProjectsStore); // <-- {}
// Why ProjectsStore here is {} and
// Uncaught TypeError: undefined is not a function?
var id = ProjectsStore.getCurrentId();
// When I calling ProjectsStore.getCurrentId(); from any component it works fine.
return this.getAllForProject(id);
}
});
TasksStore.dispatchToken = Dispatcher.register(function (payload) {
var action = payload.action;
switch (action.type) {
case TasksConstants.tasksGetAll:
requestItems();
break;
case TasksConstants.tasksGetAllSuccess:
setItems(action.data);
break;
default:
return true;
}
TasksStore.emitChange();
return true;
});
module.exports = TasksStore;
It's look like you have Circular dependencies - TasksStore and ProjectsStore requiring each other.
ProjectsStore don't need to know TasksStore, remove the line:
var TasksStore = require('../stores/TasksStore');
or, if you use it, design your store to allow dependency injection, so your to classes won't dependent on each other

Categories

Resources