Why is my backbone view render putting "undefined" at the top? - javascript

Most of the render function in the following view is irrelevant, I think but I'm leaving it for completeness. I'm stepping through a list of workflow steps, noting switching the class of the li depending on various states of the thing.
var WorkStepView = Backbone.View.extend({
className: "workflowStep",
render: function() {
var output;
var arrowPlaced = false;
var self = this;
i = 0;
_.each(this.collection.models, function(s) {
var post = "";
var classname = '';
if (s.attributes["complete"] != 1) {
if (! arrowPlaced) {
classname = "current";
if (s.attributes["adminCompletable"] == 1 ) {
post = ' - <input onClick="completeStep(' + i + ');" type="button" value="Completed" />';
}
arrowPlaced = true;
}
else {
classname = "future";
}
}
else {
classname = "past";
}
output += '<li class="' + classname + '">' + s.attributes["description"] + post + '</li>';
i++;
});
this.el.innerHTML = output;
return this;
},
});
When the user selects an asset from a list elsewhere on the page, it brings up a bunch of data including this stuff. An asset "has" a workflow, which "has" many steps. The step data is stored in window.Steps, and then this is called:
function populateSteps() {
window.workStepLists = new WorkStepView({
collection: window.Steps,
el: $('#workflowSteps')[0],
});
workStepLists.render();
}
But then I get this:
There's this extraneous "undefined" up there at the top of the list. It wasn't there before fetching and rendering this model. I don't know what's up with that at all.
Help?

You are not initializing output to be anything. So, output += "foo" becomes "undefinedfoo".
Simply initialize your output variable with an empty string:
var output = '';

Related

Knockout viewModel returns undefined

I am developing a web application which tries to upload a file to a server.
I attempted to create a new ViewModel object, but it still says
undefined
This is my ojprogresslist.js:
"use strict";
define(['ojs/ojcore', 'jquery', 'knockout', 'ojs/ojcomposite','resources/components/file-upload-custom/viewModel.js', 'ojs/ojknockouttemplateutils','ojs/ojcomponentcore', 'ojs/ojlistview', 'ojs/ojprogress'],
function(oj, $, ko, Composite, viewModel, KnockoutTemplateUtils)
{
var deleteButton=
" <oj-button id='btn1' chroming='half' display='icons' on-oj-action='[[deleteItem]]'>"+
" <span class='oj-component-icon oj-panel-remove-icon'></span>"+
"</oj-button>";
var progressItemView =
" <div class='oj-flex oj-sm-justify-content-space-between'>" +
" <div class='oj-flex-item oj-flex oj-sm-flex-direction-column'>" +
" <span data-bind='text: $properties.data.name' class='oj-progresslist-name'></span>" +
" <div data-bind='text: message' class='oj-progresslist-error-message'></div>" +
' </div>' +
" <div class='oj-flex oj-sm-align-items-center'>" +
" <oj-bind-slot name='itemInfo'>" +
" <div class='oj-flex-item oj-flex oj-progresslist-info'>" +
" <span data-bind='text: $data.getSizeInBKMGT($properties.data.size)'></span>" +
' </div>' +
' </oj-bind-slot>' +
" <div class='oj-flex-item oj-flex'>" +
" <oj-progress-status status='{{status}}'" +
" progress='{{progress}}'>" +
' </oj-progress-status>' +
' </div>' +
' </div>' +
deleteButton +
' </div>';
function progressItemViewModel(context) {
var self = this;
this.deleteItem=function(event){
viewModel.deleteList(); // this is undefined
};
};
This is my fileCustom.js:
define([
'knockout',
'ojs/ojcore',
'jquery', 'ojs/ojarraydataprovider', 'fileUploadTransport/MockTransport', 'fileUploadTransport/MockUploadXhr',
'fileUploadTransport/MockTransportItem', 'ojs/ojknockout', 'ojs/ojtoolbar', 'ojs/ojbutton', 'ojs/ojfilepicker', 'resources/js/ojprogresslist'],
function (ko, oj, $, ArrayDataProvider, Transport, MockUploadXhr) {
'use strict';
function ComponentModel(context) {
var self = this;
self.noData = ko.observable(true);
self.isSimulateError = ko.observableArray([]);
self.koArray = ko.observableArray([]);
//create file upload data provider
self.dataProvider = new ArrayDataProvider(self.koArray, {keyAttributes: 'item'});
//add or remove files
self.dataProvider.addEventListener('mutate', function(event) {
if (event.detail.add != null) {
self.noData(false); // enable clear button
}
else if (event.detail.remove != null) {
self.dataProvider.getTotalSize().then(function(size) {
if (size == 0) {
self.noData(true); //disable clear button
}
});
}
});
var options = {
maxChunkSize: 3000000, //for chunkupload
xhr: MockUploadXhr
};
var transport = new Transport(options);
self.status = 200;
function getStatus() {
if (self.isSimulateError().length) {
self.status = (self.status !== 401) ? 401 : 405;
}
else {
self.status = 200;
}
return self.status;
};
//add a filesAdd listener for upload files
self.selectListener = function(event) {
var files = event.detail.files;
if (files.length > 0) {
var fileItems = transport.queue(files);
//add the new files at the beginning of the list
for (var i = 0; i < fileItems.length; i++)
{
self.koArray.unshift(fileItems[i]);
}
//simulate error status
transport.setErrorStatus(getStatus());
//upload files
transport.flush();
}
};
//clear file items from the data provider
self.filterRemove = function(statusList) {
var dataProvider = self.dataProvider;
//remove all data rows
if (! statusList || statusList.length == 0) {
return self.koArray.removeAll();
}
var statuses = {};
for (var i = 0; i < statusList.length; i++) {
statuses[statusList[i]] = true;
}
//In this demo we only fetch up to 25 data rows,
//however you can fetch any number of rows that is right for your app
var asyncIterable = dataProvider.fetchFirst({size:25})[Symbol.asyncIterator]();
return asyncIterable.next().then(
function (fetchResults) {
var data = fetchResults.value.data;
for (var i = 0; i < data.length; i++) {
var progressItem = data[i];
if (statuses[progressItem.status])
self.koArray.remove(progressItem);
}
})
};
//clear file items from the progress list
self.clearProgressList = function(event) {
console.log("hello world"+event);
self.filterRemove(['loaded', 'errored']);
};
self.deleteList = function() {
console.log("hello world");
self.filterRemove(['loaded', 'errored']);
};
}
return ComponentModel;
});
This is my HTML:
<div style="padding-top:10px"></div>
<label for="progressList">File Upload Status</label>
<div style="padding-top:5px"></div>
<oj-progress-list id="progressList" data="[[dataProvider]]">
</oj-progress-list>
</div>
I am calling viewModel.deleteList(); from the ojprogresslist.js file to filecustom.js. And I need to call the deleteList function to delete items from ArrayDataProvider.
But the error I get is
undefined
Can you please help me?
Looking through the code for the viewModel you are returning the function ComponentModel without ever calling the method (I can't remember off the top of my head if requirejs does this for you). so my guess is that the progressItemViewModel in ojprogresslist.js
should probably look like
function progressItemViewModel(context) {
var self = this;
this.deleteItem=function(event){
//not sure if the context that is passed in to the parent function is what is expected by the ComponentModel.
//so the call may be viewModel().deleteList();
viewModel(context).deleteList();
};
};
The other thing to note is that you are not using context in function ComponentModel(context){...}.

JSON return value to global variable

Simply my code looks like this:
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.
here it my real code if you need to take a look:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});
in a loop block, before one ajax complete other one will be run and this's javascript natural treatment. For your case you can call a function at the end of success event. Do something like this:
var i = 0;
doSt();
function doSt() {
var orderinvoice = 0;
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g, '')).replace(/Qty /g, '');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g, '');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', { 'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink }, function(e) {
console.log();
document.getElementById("result").innerText = document.getElementById("result").innerText + "Order #" + e.result + " Created Successfully ";
document.getElementById("invoker").innerText = "" + e.invoice;
orderinvoice = e.invoice;
if (i + 1 == table.rows.length) {
document.getElementById("result").innerText = document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
i++;
if (i < table.rows.length) doSt();
});
}
I think you need a recursive function that always deals with the first element in your rows array and then splices it off and calls itself. For example, something like this:
function getStuff(rows, results) {
if (rows.length > 0) {
var ordername = rows[0].cells[5].innerText;
$.getJSON('orderprocess.php', { 'ord_name': ordername }, function (e) {
// do some stuff
results.push('aggregate some things here?');
rows.splice(0, 1);
return getStuff(rows, results);
});
} else {
return results;
}
}
When the array is spent, results will be returned with whatever aggregate you wanted at the end of the cycle. Then, you can do as you please with the results. I think you can also manipulate the DOM inside the function as you see fit if that makes more sense. Hope this helps.

ng-grid export to CSV plugin -- how to download all data even if paged

Hi I am working with angular's ng-grid to display about 1000 rows of data. Users are allowed to view the data in the actual table 10, 20, or 100 rows at a time..but regardless of how much data they are viewing at a time, I want them to be able to download a CSV of all 1000 rows.
Is there a way to do this with the current plugin? I've been struggling for a while now since the plug in always goes to the actual ng-grid for the data to create a CSV from.
ng-grid plug in:
ngGridCsvExportPlugin = function(opts) {
var self = this;
self.grid = null;
self.scope = null;
self.init = function(scope, grid, services) {
self.grid = grid;
self.scope = scope;
function showDs() {
var keys = [];
for (var f in grid.config.columnDefs) { if (grid.config.columnDefs[f].field) { keys.push(grid.config.columnDefs[f].field); }}
var csvData = '';
function csvStringify(str) {
if (str == null) return ''; // we want to catch anything null-ish, hence just == not ===
if (typeof(str) === 'number') return '' + str;
if (typeof(str) === 'boolean') return (str ? 'TRUE' : 'FALSE') ;
if (typeof(str) === 'string') return str.replace(/"/g,'""');
return JSON.stringify(str).replace(/"/g,'""');
}
function swapLastCommaForNewline(str) {
var newStr = str.substr(0,str.length - 1);
return newStr + "\n";
}
for (var k in keys) {
csvData += '"' + csvStringify(keys[k]) + '",';
}
csvData = swapLastCommaForNewline(csvData);
var gridData = grid.data;
for (var gridRow in gridData) {
for ( k in keys) {
var curCellRaw;
if (opts != null && opts.columnOverrides != null && opts.columnOverrides[keys[k]] != null) {
curCellRaw = opts.columnOverrides[keys[k]](gridData[gridRow][keys[k]]);
} else {
curCellRaw = gridData[gridRow][keys[k]];
}
csvData += '"' + csvStringify(curCellRaw) + '",';
}
csvData = swapLastCommaForNewline(csvData);
}
var fp = grid.$root.find(".ngFooterPanel");
var csvDataLinkPrevious = grid.$root.find('.ngFooterPanel .csv-data-link-span');
if (csvDataLinkPrevious != null) {csvDataLinkPrevious.remove() ; }
var link = "data:text/csv;charset=UTF-8," + encodeURIComponent(csvData);
var csvDataLinkHtml = "<span class=\"csv-data-link-span\">";
csvDataLinkHtml += "<br><a class=\"btn hidden btn-primary exportTable2CSV\" href=" + link + " download=\"Export.csv\">CSV Export</a></br></span>" ;
fp.append(csvDataLinkHtml);
scope.$emit("exportTable2CSVLinkReady", link);
}
setTimeout(showDs, 0);
scope.catHashKeys = function() {
showDs();
hash = '';
for (idx in scope.renderedRows) { hash += scope.renderedRows[idx].$$hashKey; }
return hash;
};
scope.$watch('catHashKeys()', showDs);
};
};
You have all the data, maybe you can use ng-csv to export csv file.
Here is example. sfiddle
html:
<h2>Export {{sample}}</h2>
<div>
<button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>
javascript :
angular.module('csv', ['ngCsv']);
function Main($scope) {
$scope.sample = "Sample";
$scope.getArray = [{a: 1, b:2}, {a:3, b:4}];
}
As per your explanation it is not clear what is undefined...
have you tried accessing data through scope not grid?
As you might have observed that there is no such hook/function which will export all data at once, so i suggest to make user change page selection to display all records only after that enable CSV export option?

Google Closure introducing errors

EDIT
The lesson, learned with the help of #Alex, is that you should never put function declarations in block scope. Not that I intended to do this, but if you slip up, it can cause big problems.
I have a script file that seems to be getting compressed via Google Closure incorrectly. When I run my app with the original code, all works fine. But when I try to compress it with Google Closure, some errors get introduced.
I am NOT using the advanced option; I'm using the basic, default mode
Obviously I can't expect anyone to debug the compressed file, but I'm hoping someone can look at the uncompressed code and let me know if I'm somehow doing something insanely stupid that would trick Closure.
Some notes on the minified code:
Closure is inlining BEFramework.prototype.hstreamLoad and BEFramework.prototype.hstreamEvalJson, and seems to be utterly removing the helper functions getDeleteValue, getValueToDisplay, getDisplayForLabel and likely others.
Uncompressed file is below.
This code can manually be compiled by closure here, which should reproduce the symptoms described above.
(function() {
var $ = jQuery;
// Load and display the messages ("healthstream") for a given module.
// This requires that the module's HTML have specific features, see
// dashboard.htm and contactsManager/details/default.htm for examples.
// This also requires that the `request` support `pageIndex` and `pageSize`,
// so we can handle paging.
//
// Args: `options` An options object with these keys:
// `channelId` The channel ID of the module (for transmitRequest)
// `translationId` Optional alternate ID for translation (if not given,
// `channelId` is used).
// `action` The action (for transmitRequest)
// - Must support `pageIndex` and `pageSize`
// `request` The request (for transmitRequest)
// - Must include `pageIndex` and `pageSize`
// `complete` Optional callback triggered when the load is complete.
// `showOptions` Optional callback if an options menu is supported
// by the calling module. Receives a raw event instance
// and the item on which the options were triggered:
// function showOptions(event, item)
// `context` Optional context (`this` value) for the call to
// `complete` and/or `showOptions`
BEFramework.prototype.hstreamLoad = hstreamLoad;
function hstreamLoad(options) {
var inst = this;
var channelId, translationId, action, request, complete, showOptions, context,
pageIndex, pageCount, pageSize, pageCount,
btnPrevious, btnNext,
dataShownFlags;
// Get our arguments (with defaults)
channelId = options.channelId;
translationId = options.translationId || options.channelId;
action = options.action;
request = $.extend({}, options.request); // Create a *copy*, because we modify it when doing paging
complete = options.complete;
if (typeof complete !== "function") {
complete = undefined;
}
showOptions = options.showOptions;
if (typeof showOptions !== "function") {
showOptions = undefined;
}
context = options.context; // (undefined will automatically become the global object)
// Grab the initial pageIndex and pageSize
pageIndex = request.pageIndex || 1;
pageSize = request.pageSize || 100;
// Disable the button and show "searching" label
$('#healthStreamSearchButton')
.button("disable")
.button("option", "label", BETranslate(translationId, 'HealthStreamSearching'));
// Hook up the buttons; be a bit paranoid that they've been hooked before and clear previous handlers
btnPrevious = $('#healthStreamPagePrevious');
btnNext = $('#healthStreamPageNext');
btnPrevious.hide().unbind("click.paging").bind("click.paging", goToPreviousPage);
btnNext.hide().unbind("click.paging").bind("click.paging", goToNextPage);
// Do it
doLoad();
// === Support functions
// Trigger a load request
function doLoad() {
request.pageIndex = pageIndex;
request.pageSize = pageSize;
inst._transport.transmitRequest(channelId, action, request, hstreamLoaded);
}
// Hndle the load response
function hstreamLoaded(objResponse) {
var healthStream = objResponse.items;
var total = objResponse.total;
var tbody = $('#healthStreamList');
// Need to make this update optional
$('#pageHeaderName').html(BETranslate(translationId, 'HeaderActivity') + ' (' + String(total) + ')');
$('#healthStreamSearchButton')
.button("enable")
.button("option", "label", BETranslate(translationId, 'HealthStreamSearch'));
tbody.empty();
btnPrevious.hide();
btnNext.hide();
if (healthStream.length > 0) {
pageCount = Math.ceil(total / pageSize);
if (pageCount > 1) {
if (pageIndex > 1) {
btnPrevious.show();
}
if (pageIndex < pageCount) {
btnNext.show();
}
}
var item;
var tr;
var tdMain;
var daysHash = {};
var creationDate;
var key;
var today = new Date();
var yesterday = new Date();
var msg;
yesterday.setDate(yesterday.getDate() - 1);
dataShownFlags = {};
for (var x = 0; x < healthStream.length; x++) {
item = healthStream[x];
msg = inst.hstreamEvalJson(item);
if (msg.length > 0) {
creationDate = new Date(item.CreationDate);
key = [creationDate.getYear(), creationDate.getMonth(), creationDate.getDate()].join('-');
if (!daysHash[key]) {
if (isDateEqual(creationDate, today)) {
addRowHeader(tbody, BETranslate(inst._channelId, 'HSToday'));
}
else if (isDateEqual(creationDate, yesterday)) {
addRowHeader(tbody, BETranslate(inst._channelId, 'HSYesterday'));
}
else {
addRowHeader(tbody, creationDate.toString('MM/dd/yyyy'));
}
daysHash[key] = true;
}
tr = $(
"<tr>" +
"<td class='date' style='white-space:nowrap;'>" + new Date(item.CreationDate).toString('h:mm tt') + "</td>" +
"<td class='main'><span class='name'>" + msg + "</span>" +
"</tr>"
);
tbody.append(tr);
if (showOptions) {
tr.find("td.main").prepend($("<em rel='opt'> </em>").click(makeShowOptionsHandler(item)));
}
}
}
// If any of the templates created links with a `data` attribute, hook them up
$('#healthStreamList a[data]').click(showTitle).each(function (index) {
this.id = 'data' + index;
});
}
else {
tbody.html('<tr><td colspan="2">' + BETranslate(inst._channelId, 'HSNoActivity') + '</td></tr>');
}
// Trigger completion callback
if (complete) {
complete.call(context, objResponse);
}
}
function makeShowOptionsHandler(item) {
// Our event comes to us from jQuery, but we pass on the raw
// event to the callback
return function (event) {
showOptions.call(context, event.originalEvent || event, item);
};
}
function addRowHeader(listRef, name) {
listRef.append(
"<tr>" +
"<td colspan='2' class='divider'>" + name + "</td>" +
"</tr>"
);
}
function showTitle(event) {
$.stopEvent(event);
var link = this;
var $link = $(this);
var href = $link.attr("href"); // We want the attribute, not the property (the property is usually expanded)
var hrefTitle = $link.attr('hreftitle') || BETranslate(inst._channelId, 'HSMoreInfo');
var data = $link.attr('data') || "";
var linkId = link.id;
if (!dataShownFlags[linkId]) {
dataShownFlags[linkId] = true;
if (data) {
var div = $(
"<div class='data'>" +
"<span data-linkId='" + linkId + "' class='close'>x</span>" +
"<table><thead></thead></table>" +
"</div>"
);
$link.parent().append(div);
var thead = div.find("thead");
var arr = data.split('~');
var splitEntry;
for (var x = 0; x < arr.length; x++) {
splitEntry = arr[x].split('|');
if (splitEntry[0] === 'Changed length') {
splitEntry[1] = splitEntry[1].replace(/\d+/g, BEFramework.prettyTime);
}
if (splitEntry.length > 1 && splitEntry[1].length > 0) {
thead.append(
"<tr>" +
"<td class='hslabel'>" + splitEntry[0] + ":</td>" +
"<td>" + splitEntry[1] + "</td>" +
"</tr>"
);
}
}
div.find("span:first").click(hideTitle);
if (href && href !== "#") {
$("<a target='_blank'>" + hrefTitle + "</a>").attr("href", href).appendTo(div);
}
}
}
}
function hideTitle(event) {
var $this = $(this),
linkId = $this.attr("data-linkId");
delete dataShownFlags[linkId];
$this.parent().remove();
return false;
}
function goToPreviousPage(event) {
--pageIndex;
doLoad();
return false;
}
function goToNextPage(event) {
++pageIndex;
doLoad();
return false;
}
}
var ___x = false;
var __i = 0;
BEFramework.prototype.hstreamEvalJson = hstreamEvalJson;
function hstreamEvalJson(item) {
var inst = this;
if (item.Action === 'saveinsurance' && !___x && __i != 0){
var start = +new Date();
__i = 1;
}
var userId = inst._BEUser ? inst._BEUser.getId() : -1;
var json = eval('(' + item.JSON + ')');
var key = 'HS' + item.Module + '_' + item.Action;
var msg = BETranslate(inst._channelId, key);
var fromIsMe = item.CreatedByContactId == userId;
var toIsMe = item.ContactId == userId;
var fromString = (fromIsMe) ? '<strong>' + BETranslate(inst._channelId, 'HSYou') + '</strong>' : '<a class="vcard" contactId="' + item.CreatedByContactId + '">' + item.CreatedByName + '</a>';
var toString = (toIsMe) ? '<strong>' + BETranslate(inst._channelId, 'HSYour') + '</strong>' : '<a class="vcard" contactId="' + item.ContactId + '">' + item.ContactName + '</a>';
var fromString2 = (fromIsMe) ? '<strong>' + BETranslate(inst._channelId, 'HSYour').toLowerCase() + '</strong>' : '<a class="vcard" contactId="' + item.CreatedByContactId + '">' + item.CreatedByName + '</a>';
var toString2 = (toIsMe) ? '<strong>' + BETranslate(inst._channelId, 'HSYou').toLowerCase() + '</strong>' : '<a class="vcard" contactId="' + item.ContactId + '">' + item.ContactName + '</a>';
var subFormat, subProps;
var configObject = (BEFramework.healthStreamConfig[item.Module] && BEFramework.healthStreamConfig[item.Module][item.Action]) || {};
var standardCase = configObject.standardCase;
var suppress = configObject.suppress || [];
var propertiesInOrder = configObject.displayOrder || [];
if (msg.indexOf('not found in module') != -1) {
try {
switch (item.Module) {
case 'contacts':
if (item.Action == 'setpermission' || item.Action == 'deleterelationship' || item.Action == 'addinvite') {
msg = BETranslate(inst._channelId, key + json.type.toString());
}
break;
case 'tasks':
if (item.Action == 'savetask') {
msg = BETranslate(inst._channelId, key + json.type.toString());
}
break;
default:
msg = '';
}
} catch (ex) {
msg = '';
}
}
for (var prop in json) {
if (typeof (json[prop]) == 'object') {
if (prop === 'changes' || prop === 'deleted'){
subProps = json[prop];
for (var propName in subProps) {
if (indexInArrayCI(propName, propertiesInOrder) === -1 && indexInArrayCI(propName, suppress) === -1){
propertiesInOrder.push(propName);
}
}
}
if (prop == 'changes') {
var changes = '';
var changeFrom = BETranslate(inst._channelId, 'HSChangedFrom');
var changeTo = BETranslate(inst._channelId, 'HSChangedTo');
for (var i = 0; i < propertiesInOrder.length; i++) {
var subprop = propertiesInOrder[i];
if (getObjectValCI(subProps, subprop) == null) continue;
var subSplit = stripHtml(getObjectValCI(subProps, subprop)).split('|');
if (subSplit.length === 1) {
subFormat = BETranslate(inst._channelId, 'HS' + item.Module + '_changes_' + subprop);
if (subFormat.indexOf('not found in module') < 0) {
changes += $.sandr(subFormat, '#{value}', subSplit[0]);
}
else {
changes += "*|" + subprop + " " + subSplit[0] + "~";
}
}
else {
var fromValue = stripHtml(subSplit[0]);
var toValue = stripHtml(subSplit[1]);
var packetInfo = processChangedValues(subprop, fromValue, toValue);
if (packetInfo.skip) continue;
changes = changes + changeFrom + packetInfo.display + '|' + packetInfo.fromValue + '<b>' + changeTo + '</b>' + packetInfo.toValue + '~';
}
}
msg = $.sandr(msg, '#{' + prop + '}', changes);
} else if (prop == 'deleted') {
var deleted = '';
for (var i = 0; i < propertiesInOrder.length; i++) {
var subprop = propertiesInOrder[i];
var currentValue = getObjectValCI(subProps, subprop);
if (currentValue == null || currentValue.toString().length === 0) continue;
deleted = deleted + getDisplayForLabel(subprop) + '|' + getDeleteValue(subprop, currentValue) + '~';
}
msg = $.sandr(msg, '#{' + prop + '}', deleted);
}
} else {
msg = $.sandr(msg, '#{' + prop + '}', $.sandr(json[prop], '"', ' '));
}
function processChangedValues(label, fromValue, toValue){
var typeFormat = (getObjectValCI(configObject, label) || {}).type;
var result = {};
if (typeFormat === 'date'){
var d1 = new Date(fromValue);
var d2 = new Date(toValue);
if (isDateEqual(d1, d2)) result.skip = true;
}
result.fromValue = getValueToDisplay(fromValue, typeFormat);
result.toValue = getValueToDisplay(toValue, typeFormat);
result.display = getDisplayForLabel(label)
return result;
}
function getDeleteValue(label, value){
var typeFormat = (getObjectValCI(configObject, label) || {}).type;
return getValueToDisplay(value, typeFormat);
}
function getValueToDisplay(rawValue, typeFormat){
if (typeFormat === 'date'){
var d = new Date(rawValue);
return isNaN(d.getTime()) ? rawValue : d.toString('MM/dd/yyyy');
} else if (typeof typeFormat === 'function') {
return typeFormat(rawValue)
} else {
return rawValue;
}
}
function getDisplayForLabel(label){
var fixCaseOfProperty = standardCase === '*' || indexInArrayCI(label, standardCase) > -1;
var rawConfigForLabel = getObjectValCI(configObject, label) || {};
return (rawConfigForLabel && rawConfigForLabel.display)
|| (fixCaseOfProperty ? fixCase(label) : null)
|| label;
}
}
msg = $.sandr(msg, '#{contactId}', item.ContactId);
msg = $.sandr(msg, '#{from}', fromString);
msg = $.sandr(msg, '#{to}', toString);
msg = $.sandr(msg, '#{from2}', fromString2);
msg = $.sandr(msg, '#{to2}', toString2);
msg = $.sandr(msg, '#{recordId}', item.RecordId);
msg = msg.replace(/#{[\S]*}/g, '');
if (item.Action === 'saveinsurance' && !___x && __i == 1){
var end = +new Date();
___x = true;
//alert(end - start);
}
if (item.Action === 'saveinsurance') __i++;
if (msg.indexOf('not found in module') == -1) {
return msg;
} else {
return '';
}
}
function stripHtml(html) {
var tmp = document.createElement('DIV');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText;
}
function isDateEqual(date1, date2) {
if (date1.getDate() === date2.getDate() &&
date1.getMonth() === date2.getMonth() &&
date1.getYear() === date2.getYear()) {
return true;
}
else {
return false;
}
}
function getObjectValCI(obj, key){
for (var k in obj){
if (k.toLowerCase() === key.toLowerCase()){
return obj[k];
}
}
}
function indexInArrayCI(item, arr){
if (!$.isArray(arr)) arr = [];
var target = item.toString().toLowerCase();
for (var i = 0; i < arr.length; i++){
if (target === arr[i].toLowerCase()) return i;
}
return -1;
}
function fixCase(str){
return str.replace(/[a-z][A-Z]/g, function(match) { return match.charAt(0) + ' ' + match.charAt(1).toLowerCase(); }).toLowerCase()
.replace(/\sid\s/g, ' ID ')
.replace(/\sid$/g, ' ID')
.replace(/^id$/g, 'ID');
}
})();
When you use closure compiler you're giving up some control over your code. It will do all sorts of tricks, and potentially remove unused code.
It appears as though your functions are not removed, but are renamed.
For example, your call to getDeleteValue...
getDeleteValue(subprop, currentValue)
is now...
l(g,r)
Because getDeleteValue was not exported, Closure renamed it.
Working with Closure Compiler takes a bit of finesse and quite a bit of documentation scouring until you're familiar with how it works.
Well, there are too many errors to think of. First of all, I don't understand if you want static reference or instantiated values. You are not using jsDoc tags or anything like that. The Compiler does it's best work only with the corresponding jsDoc tag. You're logic is very weird and ill formulated. Prototype alternations, etc, all happening in an IIFE(immediately invoked function expression). Are your functions static? Are they constructors? Are we human or are we dancer?
an IIFE executes before the DOMContentLoaded event is fired by the browser. The most you can do is a jQuery IIFE equivalent $(function() {})(); which binds that to the DOMReady or DOMContentLoaded callback. You are defining inline functions inside blocks, which is not even in the ECMA Language.
While most script engines support Function Declarations within blocks it is not part of ECMAScript (see ECMA-262, clause 13 and 14). Worse implementations are inconsistent with each other and with future EcmaScript proposals. ECMAScript only allows for Function Declarations in the root statement list of a script or function. Instead use a variable initialized with a Function Expression to define a function within a block.
var myFunctionName = function (params) {};
You are also missing loads of semi-colons. Automatic semi-colon insertion on interpretation of your JS is not exactly flawless, so make a habit out of it.
Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that.
There are a couple places where missing semicolons are particularly dangerous:
// 1.
MyClass.prototype.myMethod = function() {
return 42;
} // No semicolon here.
(function() {
// Some initialization code wrapped in a function to create a scope for locals.
})();
var x = {
'i': 1,
'j': 2
} // No semicolon here.
// 2. Trying to do one thing on Internet Explorer and another on Firefox.
// I know you'd never write code like this, but throw me a bone.
[normalVersion, ffVersion][isFF]();
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
// 3. conditional execution a la bash
-1 == resultOfOperation() || die();
So what happens?
JavaScript error - first the function returning 42 is called with the second function as a parameter, then the number 42 is "called" resulting in an error.
You will most likely get a 'no such property in undefined' error at runtime as it tries to call x[ffVersion][isIE]().
die is called unless resultOfOperation() is NaN and THINGS_TO_EAT gets assigned the result of die().
Why?
JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. In each of these examples, a function declaration or object or array literal is used inside a statement. The closing brackets are not enough to signal the end of the statement. Javascript never ends a statement if the next token is an infix or bracket operator.
This has really surprised people, so make sure your assignments end with semicolons.

Find and Replace for whole page

I'm trying to create a Find and Replace for the whole page.
I'm Using findandreplace which is a mini-plugin which is:
function findAndReplace(searchText, replacement, searchNode) {
if (!searchText || typeof replacement === 'undefined') {
alert("Please Enter Some Text Into the Field");
return;
}
var regex = typeof searchText === 'string' ?
new RegExp(searchText, 'g') : searchText,
childNodes = (searchNode || document.body).childNodes,
cnLength = childNodes.length,
excludes = 'html,head,style,title,link,meta,script,object,iframe';
while (cnLength--) {
var currentNode = childNodes[cnLength];
if (currentNode.nodeType === 1 &&
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
arguments.callee(searchText, replacement, currentNode);
}
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
continue;
}
var parent = currentNode.parentNode,
frag = (function(){
var html = currentNode.data.replace(regex, replacement),
wrap = document.createElement('div'),
frag = document.createDocumentFragment();
wrap.innerHTML = html;
while (wrap.firstChild) {
frag.appendChild(wrap.firstChild);
}
return frag;
})();
parent.insertBefore(frag, currentNode);
parent.removeChild(currentNode);
}
}
At the moment I need the find button to make a seperate JS for each Item found. I have made it so it adds a different random ID for each found item. Now I just need the JS. When Im done with the whole this I will want it so when you click on one of the found words it has a popup(not alert) saying: "Replace Word with: {INPUT HERE}" Then it will replace just that word. I thought that would be cool.
My find code is:
document.getElementById('find').onsubmit = function() {
findAndReplace(document.getElementById('fText').value, function(hi) {
var n = Math.floor(Math.random() * 9999999999);
var s = Math.floor(Math.random() * 30);
$('#fade').after('<span id="show' + n + '" style="display:none;"></span>');
$('#show' + n + '').html(hi);
$('body').prepend("<script type='text/javascript'>$('#highlight" + n + "').click(function(){$('#fade').show();});$('#highlight" + n + "').mouseover(function(){$('#highlight" + n + "').css('background', 'blue');});$('#highlight" + n + "').mouseout(function(){$('#highlight" + n + "').css('background', 'yellow');});</sc" + "ript>");
return '<span id="highlight' + n + '" style="background: yellow;color: black;">' + hi + '</span>';
});
return false;
};
I figured out that .html cant place <script> tags into a document so I hope there is another way I can do this.
Its a little crazy looking. Mabye you can see it better and know what I want here
I hope someone can help. Thank you.
I added the following code at the end of your script. It takes input from a prompt but it will 'replace all', not just the one that you click.
$('span[id^=highlight]').live('click', function () {
replacePrompt = prompt('Replace Word with:','{INPUT HERE}');
findAndReplace(document.getElementById('fText').value, function() {
return '<span class="highlight2" style="background: white;color: black;">' + replacePrompt + '</span>';
});
return false;
})
Maybe I can work something out after going through your findAndReplace function..
UPDATE: A solution is to not use the findAndReplace plugin at all. I am still not sure but this is probably what you want.
$('span[id^=highlight]').live('click', function () {
replacePrompt = prompt('Replace Word with:','{INPUT HERE}');
$(this).text(replacePrompt);
})

Categories

Resources