Trying to access a injected dependency outside controller method - javascript

Is there possible to access a injected dependency on controller outside on it?
function clienteCreateController(ClientesService, recuperarEndereco) {
var vm = this;
vm.pesquisarCep = pesquisarCep;
}
function pesquisarCep(cep) {
recuperarEndereco.find(cep)
.success(function(data) {
parseEndereco(data).bind(this);
})
.error(function(err) {
// showAlertDanger(vm, 'Cep inválido.');
console.log(err);
});
}
I'm calling the method from a button click.
Thanks

I do not think you can access the parameter recuperarEndereco in the outside function pesquisarCep. Because inside the execution context in function pesquisarCep, the variable is recuperarEndereco is not declared at all. Same as this JSFiddle: http://jsfiddle.net/dLhmozf3/. It reports error:
function outsite () {
console.log('param: ' + param);
}
var f = function (param) {
var me = outsite;
me();
};
f();
You need to define the outside function like: function pesquisarCep(cep, recuperarEndereco) { .... And call it like pesquisarCep(cep, recuperarEndereco).

Related

Exposing JS function to global namespace

I am trying to make a function available globally. I wrapped it in an immediate function but it only works if I call a new $MyClass() inside the function. I want to be able to use it like Jquery, calling functions like this elsewhere in my project:
$MyClass('myButton').click(function(){
console.log('The button was clicked');
});
This is what I want access to:
(function() {
function $MyClass(element){
element = document.getElementById(element)
this.element = element;
return this;
}
$MyClass.prototype.click = function(callback) {
this.element.addEventListener("click", clickFunction);
function clickFunction() {
callback();
}
}
$MyClass.prototype.hover = function(inEvent, outEvent) {
this.element.addEventListener("mouseover", hoverOn);
if (outEvent != undefined) {
this.element.addEventListener("mouseout", hoverOff);
}
function hoverOn() {
inEvent();
}
function hoverOff() {
outEvent();
}
}
}());
How do I expose $MyClass to the global namespace? None of the answers I've found online have made sense to me enough to apply it to my project.

PubsubJs and *this* is undefined when subscribing to a message

I have the following code:
someClass1 = function () {
this.doStuff = function () {
PubSub.publish('topic1', { id: 1 });
}
}
someClass2 = function () {
this.forename = 'bob2';
PubSub.subscribe("topic1", function (msg, data) {
log(msg, data, this.forename);
});
}
function log() {
console.log(arguments);
}
var c1 = new someClass1();
var c2 = new someClass2();
c1.doStuff();
and I am using the pubsubjs library (https://github.com/federico-lox/pubsub.js)
The code is simple - publish a message and handle it in another class (someClass2) using PubSub
My question is that when I publish a message and handle it in someClass2, this is undefined. This occurs at the line: log(msg, data, this.forename);
This means I cant access any of the someClass2 properties/functions. What do I need to do to get the this to not be undefined? Is this possible? Are they other libraries that will help? Am I doing it wrong....
All help apprenticed! Thanks
You're passing an unbound function to subscribe. Such a function has "no idea" about this. You have to bind it:
PubSub.subscribe("topic1", (function (msg, data) {
log(msg, data, this.forename);
}).bind(this));
this is not what you expect inside the callback, just cache a copy of this as another variable outside:
someClass2 = function () {
this.forename = 'bob2';
var that = this;
PubSub.subscribe("topic1", function (msg, data) {
log(msg, data, that.forename);
});
}

In Object refer to itself anonymous function key Javascript

I have this object:
var crudConfig = function($wizard, $formModal, $deleteModal) {
'use strict';
return {
handleOnShowFormModal : function() {
$formModal.on('show.bs.modal', function(event) {
...................
this.fillForms(data);
....................
});
return this;
},
fillForms : function(data) {
//do stuff
return this;
}
}
}
The problem appears when I call the fillForms with the param.
Uncaught TypeError: this.fillForms is not a function
As the fillForms key is an anonymous function how can I call it from inside the object? On other relative questions I only found how to refer itself if the key has a string value and the I call like this: this.fillForms .
this within the callback references the $formModal element. What you need to do is store this that refer to the object in a variable before the event listener is called and use the variable within the callback to access the object.
Just like this:
handleOnShowFormModal : function() {
var _this = this
$formModal.on('show.bs.modal', function(event) {
_this.fillForms(data);
});
return this;
},

Calling a service from within another service in AngularJS

I'm attempting to call a service from within another service, then use the returned object to perform some operations. I keep running into a TypeError: getDefinitions is not a function error, however.
Below is my service is called, the service doing the calling, and my relevant controller code:
definitions.service.js:
'use strict';
angular.module('gameApp')
.factory('definitionsService', ['$resource',
function($resource) {
var base = '/api/definitions';
return $resource(base, {}, {
get: {method: 'GET', url: base}
});
}]);
utilities.service.js:
'use strict';
angular.module('gameApp')
.factory('utilitiesService', ['definitionsService', function(definitionsService) {
return {
description: description,
detail: detail,
severity: severity,
};
function description(account) {
var key = angular.isDefined(getDefinitions().ABC[account.code]) ? account.code : '-';
return getDefinitions().IDV[key].description;
}
function detail(account) {
var key = angular.isDefined(getDefinitions().ABC[account.code]) ? account.code : '-';
return getDefinitions().IDV[key].detail;
}
function severity(account) {
var key = angular.isDefined(getDefinitions().ABC[account.code]) ? account.code : '-';
return getDefinitions().IDV[key].severity;
}
var getDefinitions = function() {
definitionsService.get().$promise.then(function(data) {
return data;
});
};
}]);
controller.js:
'use strict';
angular.module('gameApp')
.controller('AccountsController', AccountsController);
AccountsController.$inject = ['$routeParams', 'customersService', 'utilitiesService'];
function AccountsController($routeParams, playersService, utilitiesService) {
var vm = this;
var playerId = $routeParams.playerId;
var getAccounts = function() {
playersService.getAccounts({
playerId: playerId
}).$promise.then(function(accounts) {
for (var i = 0; i < accounts.length; i++) {
if (angular.isDefined(accounts[i].secCode)) {
accounts[i].code = accounts[i].secCode;
accounts[i].severity = utilitiesService.severity(accounts[i]);
accounts[i].detail = utilitiesService.detail(accounts[i]);
accounts[i].description = utilitiesService.description(accounts[i]);
}
}
vm.accounts = accounts;
});
};
var init = function() {
getAccounts();
};
init();
}
Currently your service returns before your variable gets defined. That means the definition is never reached. So it is declared, as the function executes, but is undefined. Just move your variable definition to the top.
This will only prevent the definition error. Another problem is that your getDefinitions function doesn't return anything but you're calling a property on it. One solution I can think of is using a callback, that gets executed when your data is loaded:
angular.module('gameApp')
.factory('utilitiesService', ['definitionsService', function(definitionsService) {
var data;
reload();
var utils = {
description: description,
detail: detail,
severity: severity,
reload: reload,
loaded: null
};
return utils;
function reload() {
definitionsService.get().$promise.then(function(data) {
data = data;
if (utils.loaded && typeof utils.loaded === "function") {
utils.loaded();
}
});
}
function description(account) {
var key = angular.isDefined(data.ABC[account.code]) ? account.code : '-';
return data.IDV[key].description;
}
}]);
Then in your controller you could use the service like this:
utilitiesService.loaded(function(){
accounts[i].description = utilitiesService.description(accounts[i]);
})
old question but still relevant. To expand on Florian Gl's answer above if you have a service with multiple functions and one or more of those functions requires a "pre-service" function to be called for example to load some resource data in like configuration information move that service call to the top, outside of the nested function (in this case below I am dealing with the promise scenario in JavaScript):
angular.module('gameApp')
.factory('utilitiesService', ['definitionsService', function(definitionsService) {
var myFirstConfigValue = '';
// call any all services here, set the variables first
configurationService.GetConfigValue('FirstConfg')
.then(function (response) {
// set the local scope variable here
myFirstConfigValue = response;
},
function() { });
function myTestFunction() {
// make an ajax call or something
// use the locally set variable here
ajaxService.functionOneTwo(myFirstConfigValue)
.then(response) {
// handle the response
},
function(err) {
// do something with the error
});
}
}]);
Key point to note here is that if you need to load in some data you do that first outside of any other functions inside your service (e.g. you want to load some JSON data).

Expose knockout ViewMode from function to another function

I have next situation...
For some reasons I need to bind knockout ViewModel inside function and call it on specific terms.
this is my code:
if (... some conditions ...) {
var polugodiste = $("#polugodiste").val();
ApplyBindingsIzostanak(polugodiste);
$('#flip-min').change(function () {
IzostanakViewModel.selectedPolugodiste(parseInt($(this).val()));
IzostanakViewModel.GetIzostanci();
});
}
and function:
function ApplyBindingsIzostanak(polugodiste)
{
var Izostanak = function (cas, tekst) {
this.Cas = cas;
this.Tekst = tekst;
};
var IzostanakViewModel = {
selectedStatus: ko.observable(),
selectedPolugodiste: ko.observable(polugodiste),
ucenikIzostanakList: ko.observableArray([]),
GetIzostanci: function () {
.. do some code ...
}
};
ko.applyBindings(IzostanakViewModel);
}
Binding is working, but I get error when I try calling IzostanakViewModel inside my if, it says IzostanakViewModel is not defined.
Can I and how expose IzostanakViewModel from function and use it inside if statement?
NOTE*
I could try something like this:
add this code to ApplyBindingsIzostanak():
window.foo = function() {
IzostanakViewMode.GetIzostanci();
}
and then call it from if statement, but maybe there is better solution...
IzostanakViewModel is a variable within the ApplyBindingsIzostanak() function. Why don't you just return it so you have a reference to it?
function ApplyBindingsIzostanak(polugodiste)
// ...
return IzostanakViewModel;
}
var IzostanakViewModel = ApplyBindingsIzostanak(polugodiste);
$('#flip-min').change(function () {
IzostanakViewModel.selectedPolugodiste(parseInt($(this).val()));
IzostanakViewModel.GetIzostanci();
});

Categories