Loop closure returning function instead of string - javascript

I am trying to create a closure in my for loop, how ever, it keeps returning a function instead of a string.
$(function() {
var addID = function(id) {
var temp = id;
return function() {
return "http://localhost:3000/board/raptrex/" + temp;
}
};
$.get("http://localhost:3000/board/raptrex", function( data ) {
console.log(data);
var $deleteUL = $('#delete');
for (var i = 0; i < data.length; i++) {
var url = addID(data[i]._id);
console.log(url);
var $item = $('<li></li>').text(data[i].name).click(function() {
$.ajax({
type: "DELETE",
url: url
})
.done(function( msg ) {
alert( "Deleted: " + msg );
});
});
$deleteUL.append($item);
}
});
});
This returns http://localhost:3000/function%20()%20{%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20%22http://localhost:3000/board/raptrex/%22%20+%20temp;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20} when I click on my li element

You're returning a function instead of a string with addID. Try the following:
var addID = function(id) {
var temp = id;
return "http://localhost:3000/board/raptrex/" + temp;
};

Related

Value being returned from function prematurely due to asynchronous functions

So I would like to return the value json10 after both query.on have been computed. However query.on is asynchronous so I return from my function before json10 can be computed. How can I structure this function so the query.on's are completed before I return from the function?
function getJsn(mystr){
var query = doc.query(mystr);
var json10;
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
var json1 = JSON.stringify(result.rows, null, " ");
json10= json1;
var json = JSON.parse(json1);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
}
})
return json10;
}
You will need to use a callback since you are async inside getJsn
function getJsn(mystr, cb){
var query = doc.query(mystr);
var json10;
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
var json1 = JSON.stringify(result.rows, null, " ");
json10= json1;
var json = JSON.parse(json1);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
}
cb(json10);
})
}
and call it like this
getJsn(someStr, function(ret) {
console.log( ret ); // this should return json10
});

How can Actionhero receive the parameter without inputs defined?

I'm using ActionHero in node.js and Angular.js.
I am trying images send to ActionHero using $http method.
but I don't know How many images are made.
so I can't define the parameter names on action in ActionHero.
below is my source.
First. images are in object, so I change object to each parameter.
insert: function (param, next) {
var url = settings.apiUrl + "/api/online/productAdd";
var vdata = {
img_objects :param.img_objects
};
angular.forEach(param.img_objects, function (v, k) {
vdata['img_file'+(k)] = v.files;
});
commonSVC.sendUrlFile("POST", url, vdata, function (state, data) {
next(state, data);
});
}
Second. make formData in sendUrlFile like source below. and then send to actionHero.
var promise = $http({
method: method,
url: url,
headers: {
'Content-Type': undefined
},
data: params,
transformRequest: function (data) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
if(angular.isObject(value)){
if(value.lastModified > 0 && value.size > 0){
formData.append(key, value);
}else{
formData.append(key, JSON.stringify(value));
}
}else{
formData.append(key, value);
}
});
return formData;
}
});
Third. ActionHero is received. but parameter isn't defined so ActionHero can't receive.
exports.productAdd = {
name: 'online/productAdd',
inputs: {
I don't know How Many Images are made? 1~10? or 1~100?
},
authenticate: true,
outputExample: {
'result':'success'
}
So I have two Questions:
How can actionhero receive the parameter without inputs defined?
Can I object with Image Data send to ActionHero by Ajax?
Thank You.
I change reduceParams function in actionProcessor.js.
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
i can define on inputs like below.
'img_*' : {required: false}
and Then I make middleware
var actionHeroMiddleware = {
name: '-',
global: true,
priority: 1000,
preProcessor: function(data, next) {
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
next();
},
stop: function(api, next) {
next();
}
};
api.actions.addMiddleware(actionHeroMiddleware);
next();

Process javascript object from html lists

I have a html structure as,
<ul>
<li>data</li>
<li><strong>data</strong></li>
<li><span>data.name</span></li>
</ul>
I want to process it to javascript object something as below,
[
{
'index': 0,
'render': function (data) {
return data;
}
},
{
'index': 1,
'render': function (data) {
return '<strong>' + data + '</strong>';
}
},
{
'index': 2,
'render': function (data) {
return '' + data.name + '';
}
}
]
I tried this code but the data parameter which is a json object are not being resolved in render field content.
var obj = [];
$('ul li').each(function(i, content){
var row = {};
row.index = i;
row.render = function(data) {
return content;
};
obj.push(row);
});
What I am looking is this code should work,
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
It must return Example as string.
Are you looking for a string concatenation?
https://jsfiddle.net/oeavo45w/
var obj = [];
$('ul li').each(function (i, content) {
var row = {};
row.index = i;
row.render = function (data) {
console.log(111, data)
return '' + data.name + ''
};
obj.push(row);
});
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
Solution: Parse an HTML Object and Evaluate Text as data Variable
Grab content and split it on the variable name data, making sure to accommodate key names. Provide the resulting array to a render function that checks for key names and replaces the placeholders with data supplied in the render parameter.
var obj = [];
$('ul li').each(function(i, content){
var content_arr = content.innerHTML.split(/data\.?([^"<]+)?/);
var row = {};
row.index = i;
row.render = function(data) {
var return_string = '';
for ( ii in content_arr ) {
if ( ii % 2 ) {
if ( content_arr[ii] ) {
return_string += data[content_arr[ii]];
}
else if ( 'string' === typeof data ) {
return_string += data;
}
}
else { return_string += content_arr[ii]; }
}
return return_string;
};
obj.push(row);
});
// data object
var data = {};
data.name = 'EXAMPLE';
data.link = 'http://example.com';
// <span>EXAMPLE</span>
// or data string
data = 'testme';
console.log(obj[1].render(data));
// <strong>testme</strong>
http://jsfiddle.net/heksh7Lr/6/
(Ya, I'm guessing HTML template libraries will be more powerful.)

Using javascript, how convert to JSON, Java-POJO-like classes?

I want use Java-POJO-like classes in my JS project: only private fields, getters and setters.
function Event() {
var homeTeam;
var awayTeam;
var id;
var singleBets = [];
var bet;
...
this.getHomeTeam = function(){
return homeTeam;
}
this.setHomeTeam = function(data){
homeTeam = data;
}
this.getAwayTeam = function(){
return awayTeam;
}
this.setAwayTeam = function(data){
awayTeam = data;
}
this.getId = function(){
return id;
}
this.setId = function(data){
id = data;
}
this.getSingleBets = function(){
return singleBets;
}
this.setSingleBets = function(data){
singleBets = data;
}
this.getBet = function(){
return bet;
}
this.setBet = function(data){
bet = data;
}
}
I would convert my Java-POJO-like class in a JSON string to send it to the server.
I can't use JSON.stringify(myClass) because the fields are private.
So I think to use a recursive method like this...
var myJsonParse = function(data){
var result = "";
for(var propertyName in data) {
var method = propertyName;
if (method.substring(0,3)=="get"){
... data[propertyName].call() ...
}
}
return result;
}
...but before I spend many time to write it I want ask you if exist a better way to convert the Java-POJO-like object in JSON.
Thank you.
Update #1
I am ashamed of myself! This is my working (but absolutely temporary) solution:
this.toJSON = function() {
var bettableEventsString = [];
for (var i = 0, len = bettableEvents.length; i < len; i++) {
bettableEventsString[i] = bettableEvents[i].toJSON();
}
var result = JSON.stringify({
userId: userId,
championshipDayId: championshipDayId,
championshipDayName: championshipDayName
});
result = result.substring(0, result.length-1);
result += ',\n "bettableEvents" : [ ' + bettableEventsString + " ] ";
result += " } "
return result;
}
The only simple way I can think of is to add an export method:
this.toJSON = function() {
return JSON.stringify({
homeTeam: homeTeam,
awayTeam: awayTeam,
id: id,
// etc...
});
}

Javascript object and this

function robot(robotId) {
this.id = robotId;
this.parts = new Array();
this.collectParts = function() {
$.getJSON('some/url', function(json) {
for(i in json.responses) {
this.parts = json.responses[i].parts;
}
});
}
}
How do I actually assign this.parts?
Assign a reference to this (when it's in the proper scope) to a variable and use that variable in the function which has changed the scope of this. In the modified version of your code below, robotInstance is the variable I've opted to use:
function robot(robotId) {
var robotInstance = this;
this.id = robotId;
this.parts = new Array();
this.collectParts = function() {
$.getJSON('some/url', function(json) {
for(i in json.responses) {
robotInstance.parts = json.responses[i].parts;
}
});
}
}
Edit: I had written this modification last night, then decided not to post it. But based on the comment to your question by #Ӫ_._Ӫ, I decided I'd show you the way I would write your code:
var robot = function( robotId )
{
this.id = robotId;
this.parts = [];
};
robot.prototype = {
collectParts: function()
{
var robotInstance = this;
$.getJSON(
'some/url',
function( json )
{
var i,
responses = json.responses;
for( i in responses )
{
if( Object.prototype.hasOwnProperty.call( responses, i ) )
{
robotInstance.parts = responses[i].parts;
}
}
}
);
}
};
To access this inside jQuery functions, you need to assign it to another variable, for instance, self = this; then replace this with self.
You can capture "this" in a "that" variable so that it can be used inside the scope of the callback of your $.getJSON
function robot(robotId) {
this.id = robotId;
this.parts = new Array();
var that = this;
this.collectParts = function() {
$.getJSON('some/url', function(json) {
for(i in json.responses) {
that.parts = json.responses[i].parts;
}
});
}
}
Just assign this to another variable e.g that
function robot(robotId) {
var that = this;
that.id = robotId;
that.parts = new Array();
that.collectParts = function() {
$.getJSON('some/url', function(json) {
for(i in json.responses) {
that.parts = json.responses[i].parts;
}
});
}
}

Categories