return array from function javascript - javascript

I need to return my behaviors but its not working
function getBehaviorList() {
var behaviors = getBehaviors();
console.log("Making behavior list");
console.log(behaviors);
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr:last').after('<tr><td>' + value.split('/').pop() + '</td><td><span class="text-color-green glyphicon glyphicon-play-circle"></span> Start</td></tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
}
function getBehaviors() {
console.log("Getting behaviors");
session.service("ALBehaviorManager").done(function (behaviorManager) {
behaviorManager.getUserBehaviorNames().done(function (behaviors) {
behaviors;
console.log(behaviors);
return behaviors;
});
}).fail(function (error) {
console.log("An error occurred: ", error);
});
}
this is the error i get in the console
Getting behaviors
Making behavior list
undefined
Uncaught TypeError: Cannot read property 'length' of undefined
["User/.lastUploadedChoregrapheBehavior/test","User/actura-test/test", "User/check-update", "User/follow-me"]
dose anyone got an idea why?

You can't return a value from the middle of a callback inside your function. That is quite likely an asynchronous call (or two it appears).
You can use deferreds or promises to do this. Here is a simple example using a callback:
function getBehaviorList() {
getBehaviors(function (behaviors) {
console.log("Making behavior list");
console.log(behaviors);
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr: last ').after(' < tr > < td > ' + value.split(' / ').pop() + ' < /td><td><a href="#" class="btn btn-default" id="' + value + '"><span class="text-color-green glyphicon glyphicon-play-circle"></span > Start < /a></td > < /tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
});
}
function getBehaviors(callback) {
console.log("Getting behaviors");
session.service("ALBehaviorManager").done(function (behaviorManager) {
behaviorManager.getUserBehaviorNames().done(function (behaviors) {
console.log(behaviors);
callback(behaviors);
});
}).fail(function (error) {
console.log("An error occurred: ", error);
callback(); // Possibly callback with [] instead.
});
}
Using deferreds is probably a better pattern, but takes more work and I would need to know more about the services you are calling.

You are call in upon getBehaviours() --> getting behaviors
Next you are making an async call (it does not have a direct answer timewise, but later.
You are returning to getBehaviorList without any returned values (undefined), which has no length.
Then later you receive the answer from getUserBehaviorNames and the console.log(behaviors).
You need to call a new function from .done()
function continueBuildBehaviorList(behaviors) {
$.each(behaviors, function (index, value) {
if (value.indexOf("User/.lastUploadedChoregrapheBehavior") < 0) {
$('#installedBehaviors tr:last').after('<tr><td>' + value.split('/').pop() + '</td><td><span class="text-color-green glyphicon glyphicon-play-circle"></span> Start</td></tr>');
}
});
$("#installedBehaviors a").click(function () {
startBehavior(this);
});
}

Related

onClick - Call Function from Another File

I have a functionality.js file which is linked to the front-end, within here I want to click on a div(item1wrapper) and call a function from my index.js file.
Within this functionality.js file I append the div:
socket.on('response', function (data) {
if (msg.includes('totalPrice')) {
if (parsed.itemPrice.length === 1) {
$('#messages').append($('<li id="messageclient">').append($(`
<div id="message-cont" class="message-cont">
<div class="orderDetailsWrapper">
<div class="detailsHeaderWrapper">
<div class="orderNum"></div>
<div class="customerName"></div>
</div>
<div class="textToCustomer">
<p> Please click on the item you want to return</p>
</div>
<div class="itemBoxWrapper">
<div id ="item1Wrapper" class="item1Wrapper" onclick="">
<div class="item1Title"></div>
<div class="item1Price"></div>
</div>`
)).append($('<div id="client-imgorder">')));
$("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight }, 1000);
$('.customerName').text('Customer name: ' + customerName);
$('.orderNum').text('Order number: ' + orderNum);
$('.item1Title').text('Item: ' + item1Title);
$('.item1Price').text('Price: ' + item1Price);
}
Module exports isnt working because it's linked to the front-end?
Here is my function within my index.js file:
function oneCall() {
itemId = itemIdArray[0];
// matching API get
// getRefundCalc API post.
console.log('ngrokurl' + ngrokUrl)
console.log('domain' + domain)
console.log('orderId' + orderId)
console.log('itemId' + itemId)
/*
The Purchase date must be in the future
*/
rp(optionsPOST1)
.then(function (parsedBody) {
Match = parsedBody.Match;
if (Match) {
console.log('Match is true');
httpRequest.post(
`${ngrokUrl}/${domain}/${orderId}`,
{
json:
{
"line_items": [
{
"line_item_id": itemId, "quantity": 1
}
]
}
},
function (error, resp, body) {
if (!error && resp.statusCode == 200) {
console.log(body)
response = responseToFrontEnd
data = [details.chatuser, response]
io.of('/main').to(socket.id).emit('response', data);
}
else {
console.log('error' + error)
}
}
)
// include getRefundCalc within here
} else {
console.log('Match is false');
response = `I'm sorry but your item fell out of the refund policy. Please check the purchase date of your item or if it falls under the minimum price.`
}
});
}
Currently the "onclick" is empty because it wasnt working, when I click on that div in this functionality.js file I want to call that function! and it has to be outside of the functionality file as it requires node modules and needs to be within the socket function!

Filter JSON object with Array of selected checkbox

How i can filter my JSON object with array.
FIDDLE
This is an sample of my json object and code, i want to filter final render HTML by selected checkbox.
Thanks for your help
function init(arr){
var li = '';
$.each(jsn, function (key, value) {
if (arr.length == 0) {
li += '<li>' + jsn[key].name + '</li>';
}else{
$(arr).each(function (i, v) {
// this section must be filter "pack's" but i can't writ correct query
li += '<li>' + jsn[key].name + '</li>';
});
};
$('#container').html(li);
})
}
var CheckArr = new Array();
init(CheckArr);
$('#btnFilter').click(function(){
var CheckArr = new Array();
$('input[type=checkbox]').each(function () {
if ($(this).is(':checked')) {
CheckArr.push($(this).attr('value'))
}
});
init(CheckArr);
First of all, you have to verify length of array outside of init function. (for case when function is called for first time).Then, you need to iterate your checkboxes array and search every item in your json array(called jsn) to verify condition you need.
Here is solution:
$(document).ready(function(){
var jsn = [
{
"name":"pack01",
"caplessthan100mb":"False",
"cap100to500mb":"True",
"cap500mbto2g":"False",
"cap2gto10g":"False"
},
{
"name":"pack02",
"caplessthan100mb":"True",
"cap100to500mb":"False",
"cap500mbto2g":"False",
"cap2gto10g":"False"
},
{
"name":"pack03",
"caplessthan100mb":"False",
"cap100to500mb":"False",
"cap500mbto2g":"False",
"cap2gto10g":"True"
},
{
"name":"pack04",
"caplessthan100mb":"False",
"cap100to500mb":"False",
"cap500mbto2g":"True",
"cap2gto10g":"False"
},
{
"name":"pack05",
"caplessthan100mb":"False",
"cap100to500mb":"False",
"cap500mbto2g":"False",
"cap2gto10g":"True"
},
{
"name":"pack06",
"caplessthan100mb":"True",
"cap100to500mb":"False",
"cap500mbto2g":"False",
"cap2gto10g":"False"
},
{
"name":"pack07",
"caplessthan100mb":"False",
"cap100to500mb":"False",
"cap500mbto2g":"False",
"cap2gto10g":"True"
}
];
function init(arr){
var li = '';
if(arr.length==0)
{
$.each(jsn, function (key, value) {
li+= '<li>' + jsn[key].name + '</li>';
});
}
else{
$(arr).each(function (i, v) {
$.each(jsn, function (key, value) {
if(jsn[key][v]=="True")
li+= '<li>' + jsn[key].name + '</li>';
});
});
}
$('#container').html(li);
}
var CheckArr = new Array();
init(CheckArr);
$('#btnFilter').click(function(){
var CheckArr = new Array();
$('input[type=checkbox]').each(function () {
if ($(this).is(':checked')) {
CheckArr.push($(this).attr('value'))
}
});
init(CheckArr);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><input type="checkbox" value="caplessthan100mb">caplessthan100mb</li>
<li><input type="checkbox" value="cap100to500mb">cap100to500mb</li>
<li><input type="checkbox" value="cap500mbto2g">cap500mbto2g</li>
<li><input type="checkbox" value="cap2gto10g">cap2gto10g</li>
<li><input type="button" id="btnFilter" value="Filter"></li>
</ul>
<br />
<ul id="container">
</ul>
There are quite a few things in your code that could use improvement so I've taken the liberty of largely rewriting it (see jsFiddle link below).
1) First thing is in your data (jsn) you are using "False" and "True" instead of false and true. That'll make it hard to write your filter condition because true != "True".
2) It's quite hard to debug your code because the variable names aren't very meaningful. I'd highly recommend putting some energy into improving your variable names especially when code isn't working.
For example:
packsData instead of jsn
checkedBoxes instead of arr
3) If you try to filter within the .each() below you'll run into trouble when it matches more than one filter condition (it'll be displayed more than once).
$(arr).each(function (i, v) {
// this section must be filter "pack's" but i can't writ correct query
li += '<li>' + jsn[key].name + '</li>';
});
Here is a working jsFiddle

Accessing Newer Version of Variable from Different Scope (JavaScript / jQuery)

I want to populate the results div with the already loaded variable, data1, when the back button is clicked. With this code, when the back button is clicked, the results div gets set to "". How do I access the newer version of data1?
Javascript:
function finddata(def,id){
$("#doctitle").html($("#exp").val() + " - Writer's Dictionary");
$("#results").html('<span class="glyphicon glyphicon-cog glyphicon-spin" title="loading..."></span>').fadeIn();
if (def == 1) {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
} else {
$.get( "processor.php?query=" + $("#exp").val(), function(data1) {
$("#results").html(data1);
});
}
}
HTML:
<div class="container">
<div class="col-md-6 col-md-offset-3" id="results">
<div id="back">Back</div>
</div>
</div>
Try
<div id="back" onclick="finddata(2)">Back</div>
to set def parameter to value other than 1 , which should call $.get() within else statement of finddata
Edit, Updated
var data;
function finddata(def) {
if (def === 1) {
// do stuff
} else {
// if `data` defined
if (data) {
// do not do stuff here
}
// else call `.get()`
else {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
}
}
}
$("#back").click(function() {
finddata(2)
})
jsfiddle http://jsfiddle.net/229ad2b2/2/

How to operate on an element inside jquery-bootgrid formatters

Suppose I have an bootgrid formatters like this:
$(document).ready(function () {
//bootgrid
$("#bootgrid-issues").bootgrid({
...
formatters: {
product: function (column, row){
return "<p class='per_online_issue_id'>" + row.product["product_name"] +"</p>";
},
category: function (column, row){
return "<p>" + row.category["category_name"] +"</p>";
},
},
});
And I want it to print an "hello" if the per_online_issue_id element clicked.
But it doesn't work as expected. Have I missed something? Here is how I do this, I wrote it right after the formatters.
$('.per_online_issue_id').click(function () {
console.log("hello")
});
Finally I myself figured out how to do this by returning javascript.
First: Return Javascript from the formatters of bootgrid.
product: function (column, row){
return "<a href=\"javascript:void(0)\" onclick=my_function(\'"+row.product["product_name"]+"\'+ "</a>";
},
Second: Call the returned my_function to operate the element you want.
<script>
function my_function(product_name) {
alert("product_name returned from bootgrid: " + production_name);
}
</script>

How do I append dynamic HTML after another piece of dynamic HTML is loaded?

I have an <OL> and a function that reads in json and loads in <li>'s. I then have another function that looks at another json and loads the final <li>. I want the first function to trigger first and then the second to append the final <li> after. However, 1 out of every 10 or so page loads the second function triggers first and the <li>s are out of order. BTW the use case is for dynamic breadcrumbs. I am using twitter bootstrap's breadcrumb class to style these elements.
First Trigger:
$.getJSON("/requirementdesc/{{ catalog }}/"+ c, function(d) {
$.each(d, function(k, v) {
$(".breadcrumb").append("<li><a href='/{{ catalog }}/"+ c +"'>"+ v.raw_requirement_desc +"</a></li>");
});
});
Second Trigger:
$.getJSON("/parentrequirement/{{ catalog }}/{{ block }}", function(data) {
$.each(data, function(key, value) {
$(".breadcrumb").append("<li class='active'>"+ value.raw_requirement_desc +"</li>");
});
});
I have tried using .promise(), but no luck.
Use jQuery's $.when(), which provides a way to execute callback functions based on one or more objects that represent asynchronous events. This code waits for both calls to complete, and then appends the lis to the ol in order.
var li_1,
li_2;
$.when(
$.getJSON("/requirementdesc/{{ catalog }}/" + c, function (d) {
$.each(d, function (k, v) {
li_1 += "<li><a href='/{{ catalog }}/" + c + "'>" +
v.raw_requirement_desc + "</a></li>";
})
}),
$.getJSON("/parentrequirement/{{ catalog }}/{{ block }}", function (data) {
$.each(data, function (key, value) {
li_2 += "<li class='active'>" + value.raw_requirement_desc + "</li>";
})
})
)
.then(function(){
if(typeof li_1 === "string" && typeof li_1 !== "undefined") {
$(".breadcrumb").append(li_1);
}
if(typeof li_2 === "string" && typeof li_2 !== "undefined") {
$(".breadcrumb").append(li_2);
}
});
Note: I didn't test this but it should theoretically work, given your code.

Categories