I'm working in React and I'm trying to pass several arguments (different sizes) to one method.
I have hard coded 8 sizes with hard coded labels and class names and that works, but it won’t work on the site since the size options will change depending on what other options are already filtered.
I need to make everything more general with more generic functions and loops.
REACT:
import React, { Component, PropTypes } from 'react';
class Sizes extends Component {
constructor(props) {
super(props);
this.state = {
XXS: false,
XS: false,
S: false,
SM: false,
M: false,
L: false,
XL: false,
XXL: false,
};
this.toggleOnOffXXS = this.toggleOnOffXXS.bind(this);
this.toggleOnOffXS = this.toggleOnOffXS.bind(this);
this.toggleOnOffS = this.toggleOnOffS.bind(this);
this.toggleOnOffSM = this.toggleOnOffSM.bind(this);
this.toggleOnOffM = this.toggleOnOffM.bind(this);
this.toggleOnOffL = this.toggleOnOffL.bind(this);
this.toggleOnOffXL = this.toggleOnOffXL.bind(this);
this.toggleOnOffXXL = this.toggleOnOffXXL.bind(this);
}
toggleOnOffXXS() {
this.setState({
XXS: !this.state.XXS
});
}
toggleOnOffXS() {
this.setState({
XS: !this.state.XS
});
}
toggleOnOffS() {
this.setState({
S: !this.state.S
});
}
toggleOnOffSM() {
this.setState({
SM: !this.state.SM
});
}
toggleOnOffM() {
this.setState({
M: !this.state.M
});
}
toggleOnOffL() {
this.setState({
L: !this.state.L
});
}
toggleOnOffXL() {
this.setState({
XL: !this.state.XL
});
}
toggleOnOffXXL() {
this.setState({
XXL: !this.state.XXL
});
}
render() {
let XXS = this.state.XXS ? 'on' : '' ;
XXS += ' filter-filterSize-XXS' ;
let XS = this.state.XS ? 'on' : '' ;
XS += ' filter-filterSize-XS' ;
let S = this.state.S ? 'on' : '' ;
S += ' filter-filterSize-S' ;
let SM = this.state.SM ? 'on' : '' ;
SM += ' filter-filterSize-SM' ;
let M = this.state.M ? 'on' : '' ;
M += ' filter-filterSize-M' ;
let L = this.state.L ? 'on' : '' ;
L += ' filter-filterSize-L' ;
let XL = this.state.XL ? 'on' : '' ;
XL += ' filter-filterSize-XL' ;
let XXL = this.state.XXL ? 'on' : '' ;
XXL += ' filter-filterSize-XXL' ;
return (
<div
className='filter-filterSize-buttons'
>
<a
className={ XXS }
href='#'
onClick={ this.toggleOnOffXXS }
>
{ 'xxs' }
</a>
<a
className={ XS }
href='#'
onClick={ this.toggleOnOffXS }
>
{ 'xs' }
</a>
<a
className={ S }
href='#'
onClick={ this.toggleOnOffS }
>
{ 's' }
</a>
<a
className={ SM }
href='#'
onClick={ this.toggleOnOffSM }
>
{ 's-m' }
</a>
<a
className={ M }
href='#'
onClick={ this.toggleOnOffM }
>
{ 'm' }
</a>
<a
className={ L }
href='#'
onClick={ this.toggleOnOffL }
>
{ 'l' }
</a>
<a
className={ XL }
href='#'
onClick={ this.toggleOnOffXL }
>
{ 'xl' }
</a>
<a
className={ XXL }
onClick={ this.toggleOnOffXXL }
>
{ 'xxl' }
</a>
</div>
);
}
}
export default Sizes;
I was suggested that it should be written in this manner:
toggleState(key) {
let state = {};
state[key] = !this.state[key];
this.setState(XXS);
}
But when I try, everything goes into loop and pretty much craches every time...
Appreciate any help on this.
I'd suggest using just one handler function and generate your links with bindings.
import React, { Component, PropTypes } from 'react';
class Sizes extends Component {
constructor(props) {
super(props);
this.state = {
XXS: false,
XS: false,
S: false,
SM: false,
M: false,
L: false,
XL: false,
XXL: false,
};
this.sizes = ['XXS', 'XS', 'S', 'SM', 'M', 'L', 'XL', 'XXL'];
}
toggleOnOff(size) {
this.setState({
[size]: !this.state.size
});
}
render() {
let XXS = this.state.XXS ? 'on' : '' ;
XXS += ' filter-filterSize-XXS' ;
let XS = this.state.XS ? 'on' : '' ;
XS += ' filter-filterSize-XS' ;
let S = this.state.S ? 'on' : '' ;
S += ' filter-filterSize-S' ;
let SM = this.state.SM ? 'on' : '' ;
SM += ' filter-filterSize-SM' ;
let M = this.state.M ? 'on' : '' ;
M += ' filter-filterSize-M' ;
let L = this.state.L ? 'on' : '' ;
L += ' filter-filterSize-L' ;
let XL = this.state.XL ? 'on' : '' ;
XL += ' filter-filterSize-XL' ;
let XXL = this.state.XXL ? 'on' : '' ;
XXL += ' filter-filterSize-XXL' ;
return (
<div
className='filter-filterSize-buttons'
>
{
this.sizes.map((size) => {
const toggleOnOff = this.toggleOnOff.bind(this, size);
return (
<a href="#" className={[size]} onClick={toggleOnOff}>{size}</a>
)
})
}
</div>
);
}
}
export default Sizes;
I did not test this, but this should fix your project.
I'm sort of trying to divine through the missing code, but I believe that last line should be: this.setState(state);
toggleState(key) {
let state = {};
state[key] = !this.state[key];
this.setState(state);
}
// or, more simply:
toggleState(key) {
this.setState({[key]: !this.state[key]});
}
Related
Try to create multiple selection table with DataTable. But the problem is, if the table is recreated multiple times. It shows error Cannot read properties of undefined (reading '_DTTT_selected') when select row table . But it's working properly on the first table generate
Here's my JS code
Error is shown when selecting row after run getTable function for the second time
function getTable(){
$("#tblDisbursement").DataTable().clear();
$("#tblDisbursement").DataTable().destroy();
var a = generateDatatables();
}
function generateDatatables() {
$.ajax({
type: "POST",
url: "${local_server}/controller/gettableFilter",
data: $("#formDDL").serialize(),
async:true,
beforeSend : function(){
showLoadingProg(true,"load data");
},
success: function(e) {
showLoadingProg(false);
console.log("ini e");
console.log(e);
if(e.status!="Success"){
$.alert("Error/ Failed");
}
console.log("oini t");
var n = [];
var a = 0;
$.each(e.data, function(e, t) {
var c = new Object;
$.each(t.loan, function(e, t) {
c.loan_acc_no = null != t.loan_acc_no ? t.loan_acc_no : "", c.loan_cif = null != t.loan_cif ? t.loan_cif : "", c.fullname = null != t.fullname ? t.fullname : "", c.loan_prd_code = null != t.loan_prd_code ? t.loan_prd_code : "", c.loan_disb_amount_needs = null != t.loan_disb_amount_needs ? t.loan_disb_amount_needs : "", c.ldi_req_date = null != t.ldi_req_date ? t.ldi_req_date : "", c.status = null != t.status ? t.status : ""
}), n[a] = c, a++
})
var e= $("#tblDisbursement").DataTable({
data: n,
order: [
[5, 'desc']
],
lengthMenu: [
[10, 25, 50, 100, 200, 300, -1],
[10, 25, 50, 100, 200, 300, "All"]
],
columns: [{
render: function(e, t, n) {
return '<input type="checkbox" class="cekbox" name="acc[]" value="' + n.loan_acc_no + '">'
},
orderable: !1
}, {
data: "loan_acc_no"
}, {
data: "fullname",
}, {
data: "loan_prd_code",
render: function(e, t, n) {
var a = "";
return String(n.loan_prd_code).includes("A06") ? "KiniGajian" : "";
}
}, {
data: "loan_disb_amount_needs",
// className: "txtRigth",
render: function(e, t, n) {
return toRp(n.loan_disb_amount_needs)
}
}, {
data: "ldi_req_date",
render: function(e, t, n) {
return null != e ? n.ldi_req_date.replace("T", " ") : ""
}
}, {
data: "status"
} /* {
render: function(e, t, n) {
var a = "";
var x = (n.cga_nik != "Public")?n.cga_nik:n.loan_cif;
// console.log(n.cga_filename);
return a = null != n.cga_filename ? "<span class="label label-success">Image</span>' : '<span class="label label-default">No Image</span>'
}
}, */
/*{
render: function(e, t, n) {
var a = '<button class="edit btn btn-xs btn-success" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-edit"></i></button>';
return a += '<button class="view btn btn-xs btn-info" id="' + n.loan_acc_no + '" value="' + n.loan_acc_no + '" ><i class=" fa fa-eye"></i></button>'
},
orderable: !1
}*/
]
});
var t = new $.fn.dataTable.TableTools(e, {
sSwfPath: "",
sRowSelector: "td:not(:last-child)",
sRowSelect: "multi",
fnRowSelected: function(e) {
console.log(e);
try {
$(e).find("input[type=checkbox]").get(0).checked = !0;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), t == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0), 0 != n && $("#btn-dis-all").removeClass("disabled")
} catch (a) {}
},
fnRowDeselected: function(e) {
try {
console..log(e);
$(e).find("input[type=checkbox]").get(0).checked = !1;
var t = -1;
$.each($(".cekbox"), function(e, n) {
t++
});
var n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), 0 == n && $("#btn-dis-all").addClass("disabled"), t == n && 1 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !1)
} catch (a) {}
},
sSelectedClass: "success"
});
$("#tblDisbursement > thead > tr > td input[type=checkbox]").eq(0).on("click", function() {
var e = this.checked,
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
}), $(this).closest("table").find("tbody > tr").each(function() {
var a = this;
e ? (t.fnSelect(a), $("#btn-dis-all").removeClass("disabled")) : (t.fnDeselect(a), n >= 1 && $("#btn-dis-all").addClass("disabled"))
})
}),
$("#tblDisbursement").on("click", "tr td input[type=checkbox]", function() {
var e = $(this).closest("tr").get(0),
n = 0;
$.each($(".cekbox:checked"), function(e, t) {
n++
});
var a = -1;
$.each($(".cekbox"), function(e, t) {
a++
}), this.checked ? (t.fnSelect(e), n > 0 && $("#btn-dis-all").removeClass("disabled"), a == n && 0 == document.getElementById("cek").checked && (document.getElementById("cek").checked = !0)) : (t.fnDeselect(e), n > 0 && 1 == document.getElementById("cek").checked && 1 == n && (document.getElementById("cek").checked = !1, $("#btn-dis-all").addClass("disabled")))
})
}
I am trying to change some data with an ajax call, but the problem is that every new call takes a little more time than the previous one.
So after 10-15 calls, the time from when the ajax request starts and when ajax returns data is like 20 seconds per request.
I also tried to debug, and it seems that the problem is that when I trigger an ajax call, it takes all that time till the controller detects the call, and after controller detects it, it gets executed and returns data immediately.
P.S. When i comment out these 2 intervals, it works perfectly. So i guess these intervals are blocking this request form happening immediately.
Also can it be a problem with Google Chrome? Because i guess in Microsoft Edge works perfectly (as far i made a test 2 times).
html:
<div class="table-responsive">
<table class="table table-condensed table-hover usersTable">
<thead>
<tr>
<th style="width: 20%">Benutzer</th>
<th></th>
<th></th>
#foreach (var item in Model.Skills)
{
<th title="#item.Name">#item.ShortName</th>
}
<th class="text-center">Extension</th>
<th class="text-center">Total Calls</th>
<th class="text-center">Calls per hour</th>
<th class="text-center">Average Call Duration</th>
</tr>
</thead>
<tbody class="usersTableBody"></tbody>
</table>
<div class="col-md-12 text-center noSignedInUser" style="display: none;">
<h4 style="color: lightgrey">There is no signed in user</h4>
</div>
js:
$(function () {
$('.usersTableBody').on('click', '.hasSkill', function () {
var userId = $(this).parent().data('id');
var skillId = $(this).data('id');
if ($(this).hasClass('skillIsActive')) {
addRemoveSkill(userId, skillId, false, $(this))
}
else {
addRemoveSkill(userId, skillId, true, $(this))
}
});
//add or remove a skill to a user with ajax
function addRemoveSkill(userId, skillId, add, element) {
$.ajax({
url: '#Url.Action("AddRemoveSkill","Home")',
data: { userId: userId, skillId: skillId, add: add },
success: function (data) {
if(data == true) {
if (add == false)
{
$(element).addClass('skillIsInactive')
$(element).removeClass('skillIsActive')
}
else {
$(element).addClass('skillIsActive')
$(element).removeClass('skillIsInactive')
}
$(element).addClass('recentlyUpdated');
hasAllSkillsDisabled($(element));
}
}
});
}
function hasAllSkillsDisabled(element) {
parent = $(element).parent();
var hasAllDisabled = true;
$.each(parent.children('td'), function (i, item) {
if ($(item).hasClass('skillIsActive'))
{
hasAllDisabled = false;
}
});
if (hasAllDisabled == true)
{
$(parent).addClass('hasAllSkillsDisabled');
}
else {
$(parent).removeClass('hasAllSkillsDisabled');
}
}
})
two other functions that gets data every 1000ms
getUserDatas();
getSkillHeader();
var detectClass = 0;
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
$.ajax({
url: '#Url.Action("GetUsersDataWithAjax", "Home")',
data: { type: type, skill: skill },
success: function (data) {
if (data.length == 0) {
$('.noSignedInUser').show();
}
else {
$('.noSignedInUser').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].agentTr');
//if that row already exists or its new
if (!tr.length)
{
//if new create html and append to table body
var dontHaveSkills = "dontHaveSkills";
if (item.hasSkills) {
dontHaveSkills = "";
}
var hasAllSkillsDisabled = "";
if (item.hasSkills && item.HasAllSkillsDisabled) {
hasAllSkillsDisabled = "hasAllSkillsDisabled";
}
var html = '';
html += '<tr data-id="' + item.Id + '" class="agentTr ' + dontHaveSkills + ' ' + hasAllSkillsDisabled + ' time' + detectClass + '">';
html += '<td>' + item.Name + '</td>';
html += '<td class="stateName"><div class="text-right ' + item.State.NameClass + '">' + item.State.Name + '</div></td>';
html += '<td class="stateCircle"><div class="statusCircle ' + item.State.CircleClass + '"</div></td>';
$.each(item.Skills, function (j, skill) {
var klasa = "";
if (skill.IsActive == true) {
klasa = "hasSkill skillIsActive";
}
else if (skill.IsActive == false) {
klasa = "hasSkill skillIsInactive";
}
else {
klasa = "unableSkill";
}
html += '<td data-id="' + skill.Id + '" class="' + klasa + '" title="' + skill.Name + '">' + skill.ShortName + '</td>';
if (j == 25) {
return false;
}
});
html += '<td class="text-center extension">' + item.Extension + '</td>';
html += '<td class="text-center totalCalls">' + item.AvgCalls.TotalCalls + '</td>';
html += '<td class="text-center callsPerHour">' + item.AvgCalls.CallsPerHour + '</td>';
html += '<td class="text-center avgCallDuration">' + item.AvgCalls.AvgCallDuration + '</td>';
html += '</tr>';
$('.usersTableBody').append(html);
}
else {
//else if its existing update datas
tr.removeClass('dontHaveSkills hasAllSkillsDisabled');
var detect = 'time' + (detectClass - 1);
tr.removeClass(detect);
if (!item.hasSkills) {
tr.addClass('dontHaveSkills');
}
if (item.hasSkills && item.HasAllSkillsDisabled) {
tr.addClass('hasAllSkillsDisabled');
}
var stateName = tr.children('.stateName');
stateName.children('div').text(item.State.Name);
stateName.children('div').removeClass('bereitName besetzName nbzName pauseName abgemeldetName');
stateName.children('div').addClass(item.State.NameClass);
var stateCircle = tr.children('.stateCircle');
stateCircle.children('div').removeClass('Online OnCall AfterTime Pause LoggedOff');
stateCircle.children('div').addClass(item.State.CircleClass);
$.each(item.Skills, function (j, skill) {
var skillElement = tr.children('td[data-id="' + skill.Id + '"]');
if (!skillElement.hasClass('recentlyUpdated')) {
skillElement.removeClass('hasSkill skillIsActive skillIsInactive unableSkill');
if (skill.IsActive == true) {
skillElement.addClass('hasSkill skillIsActive');
}
else if (skill.IsActive == false) {
skillElement.addClass('hasSkill skillIsInactive');
}
else {
skillElement.addClass('unableSkill');
}
}
else {
skillElement.removeClass('recentlyUpdated');
}
if (j == 25) {
return false;
}
});
var extension = tr.children('.extension');
var totalCalls = tr.children('.totalCalls');
var callsPerHour = tr.children('.callsPerHour');
var avgCallDuration = tr.children('.avgCallDuration');
extension.text(item.Extension);
totalCalls.text(item.AvgCalls.TotalCalls);
callsPerHour.text(item.AvgCalls.CallsPerHour);
avgCallDuration.text(item.AvgCalls.AvgCallDuration);
tr.addClass('time' + detectClass);
}
var allTr = $('tr.agentTr');
});
}
$('tr.agentTr').each(function (i, item) {
if (!$(item).hasClass('time' + detectClass)) {
item.remove();
}
});
detectClass++;
$('.usersTable').waitMe('hide');
}
});
}
function getSkillHeader() {
$.ajax({
url: '#Url.Action("GetSkillHeaderWithAjax", "Home")',
success: function (data) {
if (data.length == 0) {
$('.allSkillsHidden').show();
}
else {
$('.allSkillsHidden').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].skillTr');
if (!tr.length) {
var html = '';
html += '<tr data-id="' + item.Id + '" class="skillTr">';
html += '<th class="name">' + item.Name + '</th>';
html += '<th class="text-center waitingQueue">~</th>';
html += '<th class="text-center activeCalls">~</th>';
html += '<th class="text-center totalFreeAgents">' + item.TotalFreeAgents + '</th>';
html += '<th class="text-center totalSignedInAgents">' + item.TotalSignedInAgents + '</th>';
html += '</tr>';
$('.skillsHeaderTableBody').append(html);
}
else {
var name = tr.children('.name');
name.text(item.Name);
var totalFreeAgents = tr.children('.totalFreeAgents');
totalFreeAgents.text(item.TotalFreeAgents);
var totalSignedInAgents = tr.children('.totalSignedInAgents');
totalSignedInAgents.text(item.TotalSignedInAgents);
}
});
}
$('.skillHeaderTable').waitMe('hide');
}
});
}
//call getUserDatas method every 1 seconds
setInterval(function () {
getUserDatas();
},1000);
setInterval(function () {
getSkillHeader();
}, 1000);
C#:
public ActionResult AddRemoveSkill(string userId, string skillId, bool add)
{
try
{
var skill = _sysCfgContext.GetUserSkill(Guid.Parse(userId), Guid.Parse(skillId));
if (add)
skill.IsActive = true;
else
skill.IsActive = false;
_sysCfgContext.EditUserSkill(skill);
_sysCfgContext.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
I'm using the assumption that those two functions aren't dependent upon one another.
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
return $.ajax(function() {
//Code omitted for brevity
});
}
function getSkillHeader() {
return $.ajax(function() {
//Code omitted for brevity
});
}
getUserDatas();
getSkillHeader();
var interval = setInterval(function(){
$.when(getUserDatas(), getSkillHeader())
.then(function(resultUserDatas,resultSkillHeader)
},1000);
I have to add that this is the untested code.
After upgrading to latest Alloy1.8 update, I have started getting Script Errors for my Listview Transform functions.
[ERROR] : Script Error {
[ERROR] : column = 17;
[ERROR] : line = 4;
[ERROR] : message = "Can't find variable: PartyName";
[ERROR] : stack = "anonymous\ntemplate#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/underscore.js:1267:28\n__alloyId721#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:23:37\ntrigger#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:163:23\nreset#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:746:35\nsuccess#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:759:44\nSync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/sync/sql.js:180:51\nsync#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:108:28\nfetch#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/backbone.js:763:42\nloadInspectionDetails#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:58:43\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/inspectionProposal.js:377:26\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/appointments/appointmentContainer.js:716:56\ncreateController#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy.js:232:54\nopenNewPage#file:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/common/common.js:759:41\nfile:///Users/neo/Library/Developer/CoreSimulator/Devices/B61D305E-4B60-441E-9098-1755F6CFDB09/data/Containers/Bundle/Application/33D5C98E-FC76-4845-96B0-CE4BB43F72A3/Residential.app/alloy/controllers/dashboard/dashboardAppointments.js:615:35";
[ERROR] : }
Here is my transform function which does return transform.PartyName
function addLastInspectedDate(model) {
var transform = model.toJSON();
var appointmentDetailsCollection = Alloy.createCollection(modelConfiguration.appointmentList);
appointmentDetailsCollection.fetch({
query: {
statement: query.getAppointmentListById,
params: [ transform.AppointmentId ]
}
});
appointmentDetailsCollection.each(function(eachRecord) {
var firstName = eachRecord.get("FirstName");
var lastName = eachRecord.get("LastName");
var partyName = "";
partyName += null != firstName ? firstName : "";
partyName += "" == partyName ? null != lastName ? lastName : "" : " " + lastName;
Ti.API.info("partyName:" + partyName);
transform.PartyName = partyName;
transform.StreetName = eachRecord.get("StreetName");
var city = eachRecord.get("City");
var stateCode = eachRecord.get("StateCode");
var postalCode = eachRecord.get("PostalCode");
var addressLine2 = "";
addressLine2 += null != city ? city : "";
addressLine2 += "" == addressLine2 ? (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "") : "," + (null != stateCode ? stateCode : "") + " " + (null != postalCode ? postalCode : "");
Ti.API.info("addressLine2:" + addressLine2);
transform.AddressLine2 = addressLine2;
transform.DateLastInspected = transform.DateInspected;
transform.AppointmentId = transform.AppointmentId;
});
return transform;
}
ListView Bindings:
<ItemTemplate name="selectedInspectionProposal" height="Ti.UI.SIZE" backgroundColor="#119050">
<View height="Ti.UI.SIZE" width="Ti.UI.FILL" top="0" bottom="1" backgroundColor="#fff">
<View class="selectedInspectionData vgroup" id="inspectionDataContainerId" top="10">
<Label class="selectedGenInfo" bindId="partyName" id="partyNameId"></Label>
<Label class="selectedGenInfo" bindId="addressLineOne" id="addressLine1Id"></Label>
<Label class="selectedGenInfo" bindId="addressLineTwo" id="addressLine2Id" bottom="15"></Label>
<Label class="selectedGenInfo" bindId="inspectedDate" id="inspectedDateId" bottom="10"></Label>
</View>
</View>
</ItemTemplate>
</Templates>
<ListSection id="section" dataCollection="Inspection" dataTransform="addLastInspectedDate">
<ListItem template="inspectionProposal" partyName:text="{PartyName}" addressLineOne:text="{StreetName}" addressLineTwo:text="{AddressLine2}" inspectedDate:text="{DateLastInspected}" appointmentId:text="{AppointmentId}" selectedBackgroundColor="#119050"></ListItem>
</ListSection>
inspectionProposal.js generated with Alloy 1.8.2
function __alloyId726(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId726.opts || {};
var models = __alloyId725.models;
var len = models.length;
var __alloyId721 = [];
for (var i = 0; len > i; i++) {
var __alloyId722 = models[i];
__alloyId722.__transform = addLastInspectedDate(__alloyId722);
var __alloyId724 = {
template: "inspectionProposal",
partyName: {
text: _.template("{PartyName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineOne: {
text: _.template("{StreetName}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
addressLineTwo: {
text: _.template("{AddressLine2}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
inspectedDate: {
text: _.template("{DateLastInspected}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
appointmentId: {
text: _.template("{AppointmentId}", __alloyId722.__transform, {
interpolate: /\{([\s\S]+?)\}/g
})
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId721.push(__alloyId724);
}
opts.animation ? $.__views.section.setItems(__alloyId721, opts.animation) : $.__views.section.setItems(__alloyId721);
}
inspectionProposal.js generated with Alloy 1.7.6
function __alloyId742(e) {
if (e && e.fromAdapter) return;
var opts = __alloyId742.opts || {};
var models = __alloyId741.models;
var len = models.length;
var __alloyId737 = [];
for (var i = 0; len > i; i++) {
var __alloyId738 = models[i];
__alloyId738.__transform = addLastInspectedDate(__alloyId738);
var __alloyId740 = {
template: "inspectionProposal",
partyName: {
text: "undefined" != typeof __alloyId738.__transform["PartyName"] ? __alloyId738.__transform["PartyName"] : __alloyId738.get("PartyName")
},
addressLineOne: {
text: "undefined" != typeof __alloyId738.__transform["StreetName"] ? __alloyId738.__transform["StreetName"] : __alloyId738.get("StreetName")
},
addressLineTwo: {
text: "undefined" != typeof __alloyId738.__transform["AddressLine2"] ? __alloyId738.__transform["AddressLine2"] : __alloyId738.get("AddressLine2")
},
inspectedDate: {
text: "undefined" != typeof __alloyId738.__transform["DateLastInspected"] ? __alloyId738.__transform["DateLastInspected"] : __alloyId738.get("DateLastInspected")
},
appointmentId: {
text: "undefined" != typeof __alloyId738.__transform["AppointmentId"] ? __alloyId738.__transform["AppointmentId"] : __alloyId738.get("AppointmentId")
},
properties: {
selectedBackgroundColor: "#119050"
}
};
__alloyId737.push(__alloyId740);
}
opts.animation ? $.__views.section.setItems(__alloyId737, opts.animation) : $.__views.section.setItems(__alloyId737);
}
I've found the beautify extension in Ace editor but I don't see any examples of how to use it. Here's what I have so far:
var beautiful = ace.require("ace/ext/beautify");
beautiful.beautify();
but I get the error:
Result of expression 'e' [undefined] is not an object.
It looks like this works:
var beautify = ace.require("ace/ext/beautify"); // get reference to extension
var editor = ace.edit("editor"); // get reference to editor
beautify.beautify(editor.session);
It requires that you pass in the Ace Editor session as the first parameter. In my original question, I did not pass in any variables and that was throwing an error.
Note: It did not work well which was mentioned on the extensions release notes. It was not working well enough to use.
I didn't get it working
var beautify = ace.require("ace/ext/beautify"); // get reference to extension
Beautify was always undefined.
After a while I gave up.
And used the external Beautify library (Link)
function beatify() {
var val = editor.session.getValue();
//Remove leading spaces
var array = val.split(/\n/);
array[0] = array[0].trim();
val = array.join("\n");
//Actual beautify (prettify)
val = js_beautify(val);
//Change current text to formatted text
editor.session.setValue(val);
}
Had the same problem. Ended up building a simplified prettify method that fit my needs (which are not to have everything on the same line).
note I was using the react version of Ace Editor but same applies to JS. It does not support comments as my generated code does not contain them and you may need to expand the method if you wish to support them.
const html = prettifyHtml('<div id="root"><div class="container"><div class="row"><div class="col-lg-6">hello there<p>What <strong>is</strong> this? <br /> yes</p></div><div class="col-lg-6"></div></div></div></div>');
const scss = prettifyScss('.container { strong {color:green; background-color:white; border:1px solid green; &:hover {cursor:pointer} } }');
<AceEditor
mode="html" // or "scss"
theme="github"
defaultValue={html} // or scss
onChange={this.onChange.bind(this)}
/>
html:
export const prettifyHtml = (html) => {
let indent = 0,
mode = 'IDLE',
inTag = false,
tag = '',
tagToCome = '',
shouldBreakBefore = false,
shouldBreakAfter = false,
breakBefore = ['p', 'ul', 'li'],
breakAfter = ['div', 'h1', 'h2', 'h3', 'h4', 'p', 'ul', 'li'];
return html
.split('')
.reduce((output, char, index) => {
if (char === '<') {
tagToCome = whichTag(html, index);
shouldBreakBefore = tagToCome && breakBefore.indexOf(tagToCome) >= 0;
mode = 'TAG';
inTag = true;
output += (shouldBreakBefore ? br(indent) : '') + '<';
} else if (char === '/' && mode == 'TAG') {
mode = 'CLOSING_TAG'
inTag = true;
output += '/';
} else if (char === ' ') {
inTag = false;
output += ' ';
} else if (char === '>') {
if (mode === 'TAG' || mode === 'CLOSING_TAG') {
indent += mode === 'TAG' ? +1 : -1;
shouldBreakAfter = breakAfter.indexOf(tag) >= 0;
inTag = false;
tag = '';
}
output += '>';
output += shouldBreakAfter ? br(indent) : '';
} else {
output += char;
if (inTag) {
tag += char;
}
}
return output;
}, '');
}
sass:
export const prettifyScss = (scss) => {
let indent = 0,
closeBefore = 0;
return scss
.split('')
.reduce((output, char) => {
closeBefore++;
if (char === '{') {
indent++;
output += '{' + br(indent);
} else if (char === '}') {
indent--;
output += br(indent) + '}' + (closeBefore > 3 ? '\n' : '') + _tabs(indent);
closeBefore = 0;
} else if (char === '.') {
output += br(indent) + '.';
} else if (char === ';') {
output += ';' + br(indent);
} else {
output += char;
}
return output;
}, '');
}
helper methods:
const _tabs = (number) => {
let output = '';
for (let cnt = 0; cnt < number; cnt++) {
output += '\t';
}
return output;
}
const br = (indent) => {
return '\n' + _tabs(indent);
}
export const whichTag = (html, index) => {
let inTag = true,
tag = '';
const arr = html.split('');
for (let i = index + 1; i < index + 10; i++) {
const char = arr[i];
if (char >= 'a' && char <= 'z' && inTag) {
tag += char;
} else if (char !== '/') {
inTag = false;
}
}
return tag;
}
Faced the same issue but fixed it by adding two script files.
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ext-beautify.js"></script>
You may need to execute the beautify.beautify after window is loaded when open the page so that editor.session is initialized.
window.addEventListener('load', () => {
beautify.beautify(editor.session)
})
Ace editor use beautify only for php, - it is written in ace docs.
For me, the best solution was https://github.com/beautify-web/js-beautify
There are a lot of settings, Js/CSS/HTML beautifying, work with npm, with python, by import, by required etc.
import beautify from 'js-beautify';
// your code
beautifyHTML() {
this.html = beautify.html(this.html, {
indent_size: '2',
indent_char: ' ',
max_preserve_newlines: '5',
preserve_newlines: true,
keep_array_indentation: false,
break_chained_methods: false,
indent_scripts: 'normal',
brace_style: 'expand',
space_before_conditional: true,
unescape_strings: false,
jslint_happy: false,
end_with_newline: false,
wrap_line_length: '80',
indent_inner_html: true,
comma_first: false,
e4x: false
});
}
see more docs and settings here
In beautify file just point beautify to windows(global object) after that you can call beautify from the global object.
ext-beautify.js on row 330 add
window.beautify = exports;
Then you can use it.
vm.session = vm.editor.getSession();
beautify.beautify(vm.session);
My page gets a response from response_ajax.php with this code:
<input class="btn" name="send_button" type="button" value="check"
onClick=
"xmlhttpPost('/response_ajax.php',
'MyForm',
'MyResult',
'<img src=/busy.gif>')";
return false;"
>
I get a response; however, jQuery scripts don't work with an arrived code. I'm trying to add script inside response_ajax.php, but nothing happens:
<?php
// ... //
echo '
<div id="whois-response">
<pre>' .$str. '</pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
';
?>
xmlhttpPost function:
function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
var xmlHttpReq = false;
var self = this;
// Xhr per Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// per tutte le altre versioni di IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Quando pronta, visualizzo la risposta del form
updatepage(self.xmlHttpReq.responseText,responsediv);
}
else{
// In attesa della risposta del form visualizzo il msg di attesa
updatepage(responsemsg,responsediv);
}
}
self.xmlHttpReq.send(getquerystring(formname));
}
function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";
function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}
var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT"
|| elemType == "TEXTAREA"
|| elemType == "PASSWORD"
|| elemType == "BUTTON"
|| elemType == "RESET"
|| elemType == "SUBMIT"
|| elemType == "FILE"
|| elemType == "IMAGE"
|| elemType == "HIDDEN")
GetElemValue(elemName, element.value);
else if (elemType == "CHECKBOX" && element.checked)
GetElemValue(elemName,
element.value ? element.value : "On");
else if (elemType == "RADIO" && element.checked)
GetElemValue(elemName, element.value);
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}
I may be wrong, but I'm pretty sure you can't do multiline strings unless it is configured to do so (and running a newer version of PHP):
echo '
<div id="whois-response">
<pre>' .$str. '</pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
';
Try changing that to:
echo <<<EOD
<div id="whois-response">
<pre> $str </pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
EOD;
I think your AJAX response is a PHP error instead of the script you think it is returning.
Got it to work by adding jQuery staff as a function
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
(function($){
$(function(){
$('html').my_jQuery_staff();
});
})(jQuery);
}
Main JavaScript file with jQuery:
// ~~ jQuery ~~
$(document).ready(function () {
$.fn.my_jQuery_staff= function() {
return this.each(function() {
// Include jQuery staff here.
});
};
$('html').my_jQuery_staff();
});