Reputation:
I have some code like this:
(function() {
'use strict';
angular.module('outApp.core')
.factory('socket', socketDataService);
function socketDataService() {
var service = {
openSocket: openSocket,
closeSocket: closeSocket,
getUpdates: getUpdates,
sendUpdates: sendUpdates,
};
return service;
function openSocket() {
var contextPath = document.location.href.split('/#')[0];
var sock = new SockJS(contextPath + '/api/cart');
var stompClient = Stomp.over(sock);
stompClient.connect({}, function(frame) {
console.log('Connected ' + frame);
stompClient.subscribe("/app/cart", {}, { customerId: "4654654", cartId: "54654" });
});
}
There are other named functions as shown in the JS object named service
at the beginning but I'm excluding them for brevity.
I am trying to grant access to the functions I mentioned in the service
object using a factory constructor that should be injectable and therefore accessible in our entire app.
I have two questions: Is this the correct way to define and return the methods?
I know I can define:
var service.method = function () {
//do stuff
}
var service.anothermethod = function () {
// do other stuff
}
return service;
but for clarity, readability and style we have chosen to do it this way. I have seen another developer do it the first way but I'm not clear on what is going on.
Next question: how can I access and thus test these methods within the function? I set a debugger
at the end of the factory but I am not able to see the methods in the console.
Thanks!
Upvotes: 0
Views: 81
Reputation: 1933
Doing this:
function foo() {
bar();
function bar () {
[...]
}
}
Is basically the same thing as doing this:
function foo() {
var bar = function () {
[...]
};
bar();
}
A function is just a type of object that you can assign, pass as an argument to others functions, etc. Don't think about is as a method like in Java.
The 2 ways you're mentioning are both fine. although there is no "var" in the 2nd way:
service.method = function () {
//do stuff
};
You're just setting a property of the object, the same way you would with an int:
service.foo = 42;
Other than that, I'm not sure about what you're asking.
Upvotes: 0