javascript: when declaring a prototype method: error is invalid left hand side for assignment - javascript-objects

I am new to object oriented javascript. Trying to make an object constructor.
Here is my code
function Collection() {
this.ports = build_ports_collection();
this.all_things = build_things_collection();
this.added_things = function() {
this.added_things.total_added = 0;
var temp = this.all_things;
temp.splice($(sth).val(), 1);
this.added_things.all = temp;
};
};
Collection.ports.prototype.reload = function() {
Collection.ports = build_ports_collection();
};
Collection.all_things.prototype.reload = function() {
Collection.all_things = build_things_collection();
};
Collection.added_things.all.prototype.reload() = function() {
var temp = Collection.all_things;
temp.splice($(sth).val(), 1);
Collection.added_things.all = temp;
};
Collection.added_things.prototype.add_things = function() {
this.added_things.total_added++;
add_things();
};
Collection.added_things.prototype.remove_things = function() {
this.added_things.total_added--;
remove_things();
};
I am getting error in the line Collection.added_things.all.prototype.reload()=....
netbeans reports: invalid left hand side for assignment.
here my intention was to bind a method reload() to Collection.added_things.all so that it will be shared among all instances of Collection
What point i am missing ?

Not sure if this is the answer you're looking for, but this came to mind.
Collection.added_things.all.prototype.reload() = function() {
var temp = Collection.all_things;
temp.splice($(sth).val(), 1);
Collection.added_things.all = temp;
};
There, you are assigning stuff to the prototype of Collection.added_things.all, while
this.added_things = function() {
this.added_things.total_added = 0;
var temp = this.all_things;
temp.splice($(sth).val(), 1);
this.added_things.all = temp;
};
is the first to declare the .all on Collection.added_things - basically, you are trying to assign a value to a property/variable/pointer that does not exist until added_things is first called.

Related

how to access function parameter value inside nested AngularJS for each loop?

I am new for AngularJS and I am trying to access function parameter value inside nested angular for each loop , but that variable gets undefined error. here is my code .
var pieChart = function (_data, _fieldName) {
var data = _data;
var cost_max = 0;
var cost_min = 99999;
angular.forEach(groupBy($scope.api_data, _fieldName), function (obj, index) {
var total = 0;
var name = '';
angular.forEach(obj, function (row, i) {
name = row._fieldName;
total += 1;
})
data.push([name, total]);
if (cost_max < obj.cost) cost_max = obj.cost;
if (cost_min > obj.cost) cost_min = obj.cost;
})
$scope.chart.data = data;
$scope.loaded = 1;
}
row._fieldName is undefined here , what was the issue ? kindly help me.
var groupBy = function (xs, key) {
return xs.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
In your second angular.forEach loop, you have to replace row._fieldName with row[_fieldName].
angular.forEach(obj, function (row, i) {
name = row[_fieldName];
total += 1;
})
By writing row._fieldName, you try to get the key named _fieldName from object row instead of the real field.
Little JSFiddle

How to access a method in one object from a second object

Hi I'm new to javascript. I have one object ListModel and I am trying to access the addToModel method from a second object.
function ListModel(){
this.list = {};
}
ListModel.prototype.addToModel = function(s){
var items = s.split("\n");
for( var i =0; i<items.length-1; i++){
console.log(items[i] + "\n");
}
}
After extensive searching I have been unable to find a solution to this problem.
The second object is:
function ListMaker(){
this.model = new ListModel();
}
ListMaker.prototype.read = function(e){
var f = e.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
this.model.addToModel(contents);
document.getElementById("ta").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
In the read method I call:
this.model.addToModel(contents);
and the console returns
Cannot read property 'addToModel' of undefined
If I change the line to:
this.model = new ListModel().addToModel(contents);
then the method works as excpected.
Maybe I'm going about this the wrong way.
Any help would be appreciated.
The problem is this
http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
Once you call a function, this is no longer pointing to what you think it is.
You need to stash this in a local and then reference the local in your callback.
ListMaker.prototype.read = function(e){
var f = e.target.files[0];
var _this = this;
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
_this.model.addToModel(contents);
document.getElementById("ta").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
See it in action: http://codepen.io/anon/pen/eZrYQj

In AngularJs set a variable in forEach for each object

I am trying to run a forEach function with data from a query and I want to set a variable for each object in that data to be able to use in a ng-repeat. I keep overriding the variable and cannot wrap my head around setting the variable for each one.
CategoryCardService.query({}, function (data) {
$scope.categoryCards = data;
angular.forEach(data, function (value) {
var categoryOccupancyPercent = $filter('number')(value.occupancy_percent * 100, 0);
var categoryTotalTurnover = value.total_turnover;
var doughnut_chart_min = 0;
var doughnut_chart_max = 0;
doughnut_chart_min = categoryOccupancyPercent;
doughnut_chart_max = 100 - categoryOccupancyPercent;
data.doughnutData = [doughnut_chart_min, doughnut_chart_max];
data.display = categoryOccupancyPercent + '%';
});
});
Pass in the key and assign like that.
CategoryCardService.query({}, function (data) {
$scope.categoryCards = data;
angular.forEach(data, function (value, key) {
// ...
data[key].display = categoryOccupancyPercent + '%';
});
});

How to convert object literal to function

Is there any dynamic way to convert/clone this object:
var object = {
a: 2,
b: function(){
return this.a;
}
}
Into this kind of function object:
function object(){};
object.a = 2;
object.b = function(){
return this.a;
};
Is this possible? how can I do so dynamically?
You can just copy everything, though I would use the prototype:
function toClass(obj) {
var func = function () {};
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
func.prototype[i] = obj[i];
}
}
return func;
}
A whole other question is how useful this actually is and whether there is a better solution to the underlying problem.
Fiddle: http://jsfiddle.net/pb8mv/
It is a little bit strange that you need such a thing. If I have to guess, I think that you have an object and you want to extend it. I.e. you want to create function based on that object, so you later create multiple instances of it. That's possible and here it is a little snippet showing how:
var object = {
a: 2,
b: function(){
return this.a;
}
}
var extend = function(obj) {
return function() {
return Object.create(obj);
}
};
var Class1 = extend(object);
var ob1 = Class1();
ob1.a = 10;
var Class2 = extend(object);
var ob2 = Class2();
ob2.a = 23;
console.log(ob1.b(), ob2.b());
The result of the script is
10 23

Is there a way to iterate through a javascript object's prototype variables and functions?

This question is no longer applicable to what I'm trying to do because I have to declare the name of the pmp objects with a name.
I want to be able to associate an object with each prototype function for my class without doing it manually for each prototype.
I've tried seeing what's inside prototype with the following methods, but to no avail
myclass.prototype.length == undefined;
myclass.prototype.toString() == [object Object];
myclass.prototype == [object Object];
This is my code. In the following lines:
this.appear = _pmp(k8rModal.prototype._appear);
this.centerSlate = _pmp(k8rModal.prototype._centerSlate);
this.adjustToScreenResize = _pmp(k8rModal.prototype._adjustToScreenResize);
I run a function called '_pmp' that creates a PreMainPost object that appear,centerSlate & adjustToScreenResize will refer to. These objects have a .run() function that will first run the pre() functions then the main() function which is being defined by the constructor parameter and then finally the post() functions.
This is all the context:
k8r-modal.js
function k8rModal(DOMnamespace){
var _ = this._ = DOMnamespace+"_"; // for DOM namespacing
this.tightWrap=1;
this.visible = 0;
$('body').prepend('<div id="'+_+'stage"></div>');
this.stage = stage = $('#'+_+'stage');
stage.css({
'display':'none',
'width':'100%',
'height':'100%',
'position': 'fixed',
'left':'0px',
'top':'0px',
'opacity': '.6',
'background-color':'#333'
});
$('body').append('<div id="'+_+'slate"></div>');
this.slate = slate = $('#'+_+'slate');
slate.css({
'display':'none',
'width':'640px',
'height':'480px',
'position': 'fixed',
'left':'0px',
'top':'0px',
'background-color':'#eee'
});
var k8rModalInstance = this;
$('.'+_+'caller').on('click',function(){
k8rModalInstance.appear.run();
});
this.appear = _pmp(k8rModal.prototype._appear);
this.centerSlate = _pmp(k8rModal.prototype._centerSlate);
this.adjustToScreenResize = _pmp(k8rModal.prototype._adjustToScreenResize);
this.centerSlate.run();
this.word="asdf";
$(window).resize(function(){
alert(k8rModalInstance.word)
k8rModalInstance.adjustToScreenResize.run();
});
}
k8rModal.prototype._appear = function(){
this.that.visible = 1;
this.that.slate.show();
this.that.stage.show();
}
k8rModal.prototype._centerSlate = function(){
var wWidth, wHeight, slate = $(this.that.slate) ;
wWidth = $(window).width();
wHeight = $(window).height();
slate.css({
top: (wHeight/2 - ( slate.height()/2))+"px",
left: ( wWidth/2 - ( slate.width()/2 ) )+"px"
});
}
k8rModal.prototype._adjustToScreenResize = function(){
this.that.centerSlate.run();
}
(pre-main-post.js) pmp.js:
function _pmp(func){
return new pmp(this,func);
}
function pmp(that,func){
var func;
this.pre = new funcList();
this.post = new funcList();
this.main = func;
this.that = that;
}
pmp.prototype.run = function(arg){
this.pre.run(arg);
this.post.run(arg,this.main());
}
pmp.prototype.trim = function(){
this.pre = new funcList();
this.post = new funcList();
}
(an object that contains a list of functions)funcList.js:
function funcList(){
this.unique; // if a function can be
this.list=[];
}
funcList.prototype.add = function(func){
if (this.unique){
var passing = 1;
for(var i; i<this.list.length; i+=1){
if (list[i].toString == func.toString){
passing = 0;
}
}
if (passing){
this.list.push(func);
}
}else{
this.list.push(func);
}
}
funcList.prototype.remove = function(func){
for(var i; i<this.list.length; i+=1){
if (list[i].toString == func.toString){
this.list.splice(i,1);
}
}
}
funcList.prototype.clear = function(){
this.list = [];
}
funcList.prototype.run = function(arg){
for(var i; i<this.list.length; i+=1){
(this.list[i])(arg);
}
}
Only the prototypes for natives and functions are accessible to you. If myClass is a function, you can iterate over its prototype by using
for(var prop in myClass.prototype){
console.log(myClass.prototype[prop]);
}

Resources