return a object with parameter - javascript

I've an object called 'sheet1'
var nr = 1;
function Sheet(title){
this.div = document.createElement('div');
this.div.dataset.sheetNr = nr;
this.div.dataset.sheetTitle = title;
document.getElementById("sheets").appendChild(this.div);
nr++;
}
Sheet.prototype = {
constructor: Sheet,
get : function(data){
return this.div.dataset.data;
}
}
var sheet1 = new Sheet("Title1");
now when I call the function
sheet1.get("sheetNr");
it returns 'undefined' !...how can I solve this problem?
// console.log(data); outputs sheetNr
but when I change my function like
Sheet.prototype = {
constructor: Sheet,
get : function(){
return this.div.dataset.sheetNr;
}
}
and then call
sheet1.get();
it returns the number of the sheet...1 in this case...
http://codepen.io/anon/pen/rOXZjq?editors=101

You don't have a data attribute defined on the div you are creating sot it doesn't exist as called. When you call this.div.dataset.sheetNr you are actually hitting a defined attribute. To use the variable data as an index you need to call:
this.div.dataset[data] instead.

Related

Calling another function after value is not working

I have a simple code to call a value from another function and its not working :
function ABC() {
var ID = XYZ(id);
Logger.log(ID); //throws error not defined.
}
function XYZ(id) {
var id = "1234"
return id;
}
What I wan to do is capture the value of id from function XYZ and Logger.log it into function ABC. But this reflects error.
Still not sure what you are trying to do with your code. This code is an "Impure Function" which is not recommended in JavaScript. How much I understood your code, below are my suggestions:
First
function abc() {
var id = xyz();
Logger.log(id);
}
function xyz() {
// Add whatever logic you want here to return ID value
var id = "1234"
return id;
}
Second
function abc() {
// Pass any value as an argument based on your requirement
var results = xyz('', '', '');
Logger.log(results.id);
Logger.log(results.name);
Logger.log(results.number);
}
function xyz(id, name, number) {
// Add whatever logic you want here
var newId = id || "1234";
var newName = name || "Mask";
var newNumber = number || "1234567890";
return { id: newId, name: newName, number: newNumber };
}
Based on what suits your requirement, you can take help of these codes.
Here you go -
function ABC() {
var ID = XYZ();
Logger.log(ID); // No longer throws the error :)
}
function XYZ() {
var id = "1234"
return id;
}
You do not need two functions, here is a simple function that will return the ID passed in.
const ABC = (id) => {
return id;
}
let a = ABC(122443);
console.log(a) // output 122443

call user function in foreach loop

i have understand that i need to change the global scope of this, because in the loop this refers to the window object. But if i try to define a variable in my foreach loop via a function its not working and i dont know why although my functio returns the correct value :(
// simple class for xml import
function io() {
this.vertexes = [];
this.getVertexByID = function(id) {
this.vertexes.forEach(function(entry) {
if (id == entry.id) {
// correct element found, displayed and returned
console.log(entry);
return entry;
}
});
}
this.importXML = function(xmlString) {
cells = this.xmlToJson(xmlString);
var parent = graph.getDefaultParent();
var _this = this;
graph.getModel().beginUpdate();
try {
// addEdges
cells.XMLInstance.Edges.Relation.forEach(function(entry) {
// both will be empty but i dont understand why :(
fromVertex = _this.getVertexByID(entry.fromNode);
toVertex = _this.getVertexByID(entry.toNode);
var e1 = graph.insertEdge(parent, null, '', fromVertex, toVertex);
});
} finally {
graph.getModel().endUpdate();
}
}
Returning a value in a forEach callback has no effect. It certainly is not the return value of the function that the forEach is part of.
So change this:
this.vertexes.forEach(function (entry) {
if(id==entry.id){
//correct element found,displayed and returned
console.log(entry);
return entry;
}
});
to this:
return this.vertexes.find(function (entry) {
return id==entry.id;
});

How do you populate a dynamic variable in AngularJS

The following code gives me the error "Cannot read property PERSON1 of null". If I comment out the line where I try to assign the dynamic variable and uncomment the alert line it pops up alerts with each successive person's name.
function fillInternalRepData() {
var internalRepList = null;
console.log("Querying Table for internal reps");
queryTable(//..blabla..//, "false", function (callbackResp) {
internalRepList = callbackResp;
// alert("TRIGGERED"); //WORKS
// alert(internalRepList.length); //WORKS
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName].such = repName;
//alert(repName); //WORKS WHEN LINE ABOVE IS COMMENTED OUT
});
}); //get list of internal reps
I simply want to create/add to the $scope.internalReps object so that I can add stuff to it like $scope.internalReps.PERSON1.Name = "Whatever"; $scope.internalReps.PERSON1.Salary = 100000;
Try adding an empty object for the "internalReps" before your forEach loop. It doesn't look like you've declared the object yet, so it can't dynamically add to a null object.
$scope.internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName] = {};
$scope.internalReps[repName].such = repName;
//alert(repName);
});
var internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
internalReps[repName] = { such: "" };
internalReps[repName].such = repName;
//alert(internalReps[repName].such);
});
That worked. Thanks for the help!

Pass Arguments from One Function to Another Without Calling It

I'm trying to get either options or, ideally, dynamicTable passed from initializeTable to the applyTableFilters function and I'm having problems getting the expected values. I'm using List.js to make a table dynamic and I need to pass or recreate the dynamicTable object so I can go ahead and use it to filter the table.
Here is the function that creates the List.js object from the HTML table:
function initializeTable(options) { // initializes table to be dynamic using List.js functions
var dynamicTable = new List("table-content", options);
dynamicTable.on("updated", function (list) { // writes a message to the user if no results are found
if (list.matchingItems.length == 0) {
document.getElementById("no-results").style.display = "block";
}
else {
document.getElementById("no-results").style.display = "none";
}
});
console.log(dynamicTable);
console.log(options);
console.log(arguments.length);
applyTableFilters.bind();
}
I've tried different methods to pass the variables to the function below. I tried .call, applyTableFilters(args), and .apply, but the problem is that I do not want the function to execute from inside here, only when the click event from the button goes off (not shown in these functions).
This is the function I want to pass the object to and proceed to make the filter functions using it:
function applyTableFilters(dynamicTable) {
var form = document.getElementById("filter-form");
//console.log(options);
//var dynamicTable = new List("table-content", options);
console.log(dynamicTable);
var filters = form.querySelectorAll('input[type="checkbox"]:checked');
dynamicTable.filter(function (item) {
console.log(item);
console.log(item._values);
if (item.values().id == 2) {
return true;
}
else {
return false;
}
//var filterStrings = [];
//console.log(filters);
//for (var i = 0; i < filters.length; i++) {
// var filterVal = filters[i].value;
// var filterString = "(" + item.values().column == filterVal + ")"; // filterVal.contains(item.values().column) ||
// filterStrings.push(filterString);
// console.log(filterVal);
// console.log(filterString);
//}
//console.log(filterStrings);
//var filterString = filterStrings.join(" && ");
//console.log(filterString);
//return filterString;
});
}
I've used:
applyTableFilters.bind(this, dynamicTable/options);
applyTableFilters.bind(null, dynamicTable/options);
applyTableFilters.bind(dynamicTable/options);
Switching between the two since I don't need both passed if one ends up working, etc. I always get a mouse event passed in and that's not even the right type of object I'm looking for. How can I get the right object passed? Also all the values in the first function are not empty and are populated as expected so it's not the original variables being undefined or null. Thanks in advance.
From your initializeTable function return a function that wraps the applyTableFilters function with the arguments you want.
Then assign the returned function to a var to be executed later.
function initializeTable(options) {
var dynamicTable = new List("table-content", options);
// other stuff
return function () {
applyTableFilters(dynamicTable)
}
}
// other stuff
var applyTableFiltersPrep = initializeTable(options)
// later, when you want to execute...
applyTableFiltersPrep()
JSFiddle example

Method, doesn't set property value

I have the following code:
function Show() {
this.showId = $("#meta-show-id").val();
this.title = $("#meta-title").val();
this.season = $("#meta-season").val();
this.episode = $("#meta-episode").val();
this.storageId = $("#meta-show-id").val() + '-' + $("#meta-season").val() + '-' + $("#meta-episode").val();
this.torrents = [];
this.putioId = null;
this.status = null;
this.subtitle = null;
}
Show.prototype = {
constructor: Show,
checkStorage: function() {
var storage = new Storage();
storage.get(this.storageId, function(data){
if (jQuery.isEmptyObject(data)){
console.log("empty");
}
else {
this.subtitle = data.subtitle;
}
});
}
}
When I call the checkStorage() method on object, method checks in chrome.storage.sync for data, and sets object this.subtitle property.
But this doesn't seem to work, this.subtitle value doesn't change.
What am I doing wrong?
This is a normal result, and it happens because of scope changing. I don't know if Storage is has your own implementation (because it is used with getItem instead of get), but anyways, you are calling a method that I guess calls back the function you provide as a second argument, right?
And because this function is called from somewhere else, this is not the object that you want.
Here is a simple example: http://jsfiddle.net/6c2e6/1/
Check out logs, and see what this is. It's the Window, because my test function is at top level..

Categories