Javascript accessing parent function variable - javascript

hi I have a Question about accessing variables that are in a parent function
var DateRangePicker = function (name, clickFunction) {
this.context = name;
this.UpdateGraph = clickFunction;
this.FinalDate = function () {
var Dates = $(this.context).find("[name=datepickerText]").val().split('-');
return Dates[1];
};
this.InitialDate = function () {
var Dates = $(this.context).find("[name=datepickerText]").val().split('- ');
return Dates[0];
};
$(this.context).find("[name=UpdateDatepicker]").click(function () {
var pickerText = $(InnerContext).find('[name=datepickerText]');
var dates = pickerText.val().split('-');
UpdateGraph(InitialDate(), FinalDate());
$(context).find("[name=Toogler]").click();
});
return this;
}
How can i access the "this.UpdateGraph()" function inside the updateDatepicker click so far it sais that UpdateGraph and this.UpdateGraph doesnt exists

You can bind the this context to your handler function, to keep from having an extra scope variable:
$(this.context).find("[name=UpdateDatepicker]").click(function () {
var pickerText = $(this.InnerContext).find('[name=datepickerText]');
var dates = pickerText.val().split('-');
this.UpdateGraph(this.InitialDate(), this.FinalDate());
$(this.context).find("[name=Toogler]").click();
}.bind(this));

Related

how to properly call functions in prototype in js

How do I properly call the functions inside pretest?
I get this error: Uncaught TypeError: b.testmenow is not a function
var pretest = function () {
var MAX_NUM = 250.0;
var prebase = function (NEW_NUM) {
this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
};
prebase.prototype.testmenow = function () {
return this.NEW_NUM;
};
return prebase;
};
var b = new pretest(111);
console.log(b.testmenow());
You need to accept your input into new pretest(111) by adding n.
And then you must instantiate your prebase constructor using n.
var pretest = function (n) {
var MAX_NUM = 250.0;
var prebase = function (NEW_NUM) {
this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
};
prebase.prototype.testmenow = function () {
return this.NEW_NUM;
};
return new prebase(n);
};
var b = pretest(111);
console.log(b.testmenow());
It is strange that you have two constructors here, you can surely do this with one.
As Felix has deftly mentioned, you can call pretest(111) instead of new pretest(111).

Why would "this" in function inside angularjs service be undefined

Why would this inside function be undefined in angularjs service?
.service('SliceService', function () {
var self = this;
var Slice = function(intervals, intervalSpan) {
self.activeSlice = [];
self.hasNext = true;
self.hasPrevious = false;
self.intervals = intervals;
self.intervalSpan = intervalSpan;
}
Slice.prototype.findIntervalIndex = function (time, slice) {
slice = slice || self.intervals;
return _.findIndex(slice, function (o) {
return o.time === time;
});
};
return Slice;
})
.controller('myController', ['SliceService', function(SliceService) {
SliceService([arr], 12);
SliceService.findINtervalIndex(time);
}])
In the above example when using it in a controller, this.activeSlice throws an error TypeError: Cannot set property 'activeSlice' of undefined.
-
Update
Thanks, everyone! I've updated my example to better reflect what I'm trying to do. With the above I'm getting a TypeError: SliceService.findIntervalIndex is not a function — Also maybe a service is not fit for what I'm trying to do?
Try saving the value of "this" before accessing it inside the anonymous scope:
(function(){
'use strict';
angular.module('myServices').service('SliceService', function () {
var context = this;
var Slice = function(intervals, intervalSpan) {
context.activeSlice = [];
context.hasNext = true;
context.hasPrevious = false;
context.intervals = intervals;
context.intervalSpan = intervalSpan;
}
return Slice;
});
}());
Using Bind:
angular.module('myServices').service('SliceService', function () {
var Slice = function(intervals, intervalSpan) {
this.activeSlice = [];
this.hasNext = true;
this.hasPrevious = false;
this.intervals = intervals;
this.intervalSpan = intervalSpan;
}.bind(this);
return Slice;
});
Note:
using arrow function of javascript ES6 makes sure that this always points to the same context. so you could replace regular function with arrow function. This is however not universally supported without transpiling.
service('SliceService', ()=>{
// operations
}
Thanks to #SeedyROM and some additional google searches on angular services. This solved all my issues...
angular.module('vpower.services').service('SliceService', function () {
this.activeSlice = [];
this.hasNext = true;
this.hasPrevious = false;
this.intervals = [];
this.intervalSpan = 12;
this.findIntervalIndex = function (time, slice) {
var curTime;
slice = slice || this.intervals;
return _.findIndex(slice, function (o) {
curTime = o.time._i || o.time;
return curTime === time;
});
};
I think I was not fully understanding the way services work.

How to make a private static array in a javascript class?

I want to make a static array in a javascript class, for this I do:
var Manager = (function () {
function Manager() {
var ubications = new ArrayList();
this.ubicationsArray = function () {
return(ubication);
};
}
Manager.prototype.addUbication = function (ubication) {
Manager.ubicationsArray().add(ubication);
};
Manager.prototype.getUbication = function (index) {
return Manager.ubicationsArray().get(index);
};
Manager.prototype.sizeOfUbications = function () {
return Manager.ubicationsArray().size();
};
return Manager;
}());
Manager["__class"] = "Manager";
Where ubications is the static array and the function ubicationsArray is the public function to acces the array.
I try to use this code with:
var ubication = new Ubication(123,456);
var manager = new Manager();
manager.addUbication(ubication);
alert(manager.sizeOfUbications());
But I got this error:
Uncaught TypeError: Manager.ubicationsArray is not a function
How is the correct way to use static arrays in a javascript code?
Currently, JavaScript can only do privacy with respect to function scope.
function Manager () {
}
Manager.prototype = (function (){
var ubications = [];
return {
addUbication: function (u) {
ubications.push(u);
},
getUbication: function (index) {
return ubications[index];
},
sizeOfUbications: function () {
return ubications.length;
}
};
})();
Inside your constructor function, this.ubicationsArray assigns a property to the instance of the object, not the constructor itself.
Perhaps you want something like this:
function Manager() {
}
var ubications = new ArrayList();
Manager.ubicationsArray = function () {
return(ubication);
};
Note that this property isn't really "private". This would be more-private:
var Manager = (function () {
function Manager() {
}
var ubications = new ArrayList();
Manager.prototype.addUbication = function (ubication) {
ubications.add(ubication);
};
Manager.prototype.getUbication = function (index) {
return ubications.get(index);
};
Manager.prototype.sizeOfUbications = function () {
return ubications.size();
};
return Manager;
}());
Manager["__class"] = "Manager";

Context in javascript inheritance

We are using a oop architecture as the following, and we have a scope problem. We have the 'self' variable for saving the context, but when we call the function 'print' in the overridden class, we are using the 'self' variable instead of 'this', and we cannot override a base method.
Do someone knows how override this methods with this architecture?
var baseItem = function() {
var self = {};
self.a = function () {
console.log('base');
return 1;
};
self.print = function() {
return self.a();
}
return self;
};
var middleItem = function () {
var parent = baseItem();
var self = Object.create(parent);
return self;
}
var overrided = function () {
var parent = middleItem();
var self = Object.create(parent);
self.a = function() {
console.log('overrided');
return 55;
};
return self;
}
var obj = overrided();
overrided.print(); // This returns 1 instead 55, as we would want

Is there any other way to implement Singleton Pattern in javascript?

Trying to implement singleton pattern in javascript following some tutorials. Just wondering if there is any other way to implement the same ?
var singleton = (function(){
var getInstance; //private variable
var createWidget = function(){
var todayDate = new Date(); //private
var addCSS = function(){
console.log('THis is my css function');
};
var getDropDownData = function(){
console.log('This is my getDropDownData function');
};
return {
getDropDownData : getDropDownData,
addCSS: addCSS
};
};
return {
getInstance: function(){
if(!getInstance) {
getInstance = createWidget();
}
return getInstance;
}
};
})();
var obj = singleton.getInstance();
Implementing it by running anonymous function at onLoad and assiging it to some variable. Can we implement it without running this function at onLoad ?
You could always write a function to abstract away the boilerplate for writing singletons. For example this is what I would do:
function singleton(prototype) {
var instance = null;
return {
getInstance: function () {
if (instance === null) {
var Instance = prototype.init || function () {};
Instance.prototype = prototype;
instance = new Instance;
} return instance;
}
};
}
Then you can use this function to create singletons as follows:
var Widget = singleton({
init: function () {
var todayDate = new Date; // private
},
addCSS: function () {
console.log("This is my addCSS function.");
},
getDropDownData: function () {
console.log("This is my getDropDownData function.");
}
});
After that you use the singleton as you normally would:
var widget = Widget.getInstance();
Hope that helps.

Categories