Why does this loop seem convoluted and verbose? [closed] - javascript
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The loop below builds an HTML string using the object literal obj_fav, which holds a list of favorites.
Because the HTML string can be appended in multiple places, ns_tag namespaces the DOM ids to make sure they are unique.
This is somewhat besides the point. I feel the loop has poor logic. It works fine, but I find it hard to read and feel that is is poorly written. But I can't put my finger on why that is.
// $A.someIndex() implements array.prototype.some
// create favorite pane strings
$A.someIndex(obj_fav, function (val) {
previous_id = current_id;
current_id = this.A.ns_tag + selector + val.tag;
// new tag found, close previous and open new
if ((previous_id === undefined) || (previous_id !== current_id)) {
// populate tag array
this.A['tag_array' + selector].push(current_id);
tag_string = tag_string + this.composeTag(current_id, selector);
if (previous_id !== undefined) {
favorite_string += '</div>';
}
favorite_string = favorite_string +
'<div class="bookmark_page toggle_display_none" id = "' + current_id + '_page">';
}
// add set of favorites between page tags
favorite_string += this.composeFavorite(val, selector);
}, this);
this snippet is contained in this klass:
/*******************************************************************************
**SArcmarks
*/
var SArcmarks = $A.klass({
Name: 'SArcmarks',
// namespacing helps to prevent name clashes // base_location_id_subdivisions // there are 2 prefixes and one suffix
A: {
// namespace suffix base: 'udt' loc: null,
ns_tag: 'udt_',
ns_tag1: 'udt_1_',
tag_array: [],
tag_array1: [],
prev_page_el: null,
prev_tag_el: null,
but_text: null,
// toggles
toggle_display_none: 'toggle_display_none',
toggle_display_inline: 'toggle_display_inline',
toggle_tag_active: 'toggle_tag_active',
toggle_tag_lazy: 'toggle_tag_lazy',
// morphing
class_a: null
},
E: {
hold_arcmarks: '#hold_arcmarks',
hold_tags: '#hold_tags',
aba_but_del: '#aba_but_del',
bookmark_link: '#bookmark_link'
},
/******************************************************************************/
update: function (obj_fav, fav_el, tag_el) {
var favorite_string = '',
tag_string = '',
current_id,
previous_id,
selector;
if (fav_el) {
selector = 1;
} else {
selector = '';
}
// create favorite pane strings
$A.someIndex(obj_fav, function (val) {
previous_id = current_id;
current_id = this.A.ns_tag + selector + val.tag;
// new tag found, close previous and open new
if ((previous_id === undefined) || (previous_id !== current_id)) {
// populate tag array
this.A['tag_array' + selector].push(current_id);
tag_string = tag_string + this.composeTag(current_id, selector);
if (previous_id !== undefined) {
favorite_string += '</div>';
}
favorite_string = favorite_string +
'<div class="bookmark_page toggle_display_none" id = "' + current_id + '_page">';
}
// add set of favorites between page tags
favorite_string += this.composeFavorite(val, selector);
}, this);
// close last tag
favorite_string = favorite_string + '</div>';
// if atleast one favorite/tag
if (this.A['tag_array' + selector][0]) {
if (!fav_el) {
this.E.hold_arcmarks.innerHTML = favorite_string;
} else {
fav_el.innerHTML = favorite_string;
}
if (!tag_el) {
this.E.hold_tags.innerHTML = tag_string;
} else {
tag_el.innerHTML = tag_string;
}
this.initPane(selector);
this.flip($A.el('#' + this.A['tag_array' + selector][0]));
}
},
/******************************************************************************/
composeFavorite: function (val, selector) {
// add selector
if (val.favicon === null) {
val.favicon = 'arcmarks/images/image_null_50.png';
}
return '<div class = "am_hold" id = "' + val.id + selector + '">' +
'<img name="bo_im" id="' + $A.addU(val.id + selector, 'a') +
'" class="bookmark_image" src="' + val.favicon + '">' +
'<a target="_blank" name="bookmark_link" class="bookmark_link" href = "' +
val.url + '" id="' + $A.addU(val.id + selector, 'b') + '">' + val.title + '</a>' +
'</div>';
},
/******************************************************************************/
composeTag: function (current_id, selector) {
// selector
return '<p class="single_tag toggle_tag_lazy" id = "' + current_id + '">' +
current_id.slice(this.A['ns_tag' + selector].length) + '</p>';
},
/******************************************************************************/
// add listeners to tag(<p>) elements
initPane: function (selector) {
$A.someIndex(this.A['tag_array' + selector], function (val) {
var self = this;
$A.el('#' + val).addEventListener("click", function () {
self.flip(this);
});
}, this);
},
/******************************************************************************/
// flip page(<div>) | tag(<p>) given a tag
flip: function (tag_element) {
var page_element = $A.el('#' + tag_element.id + '_page');
$A.addClass(page_element, this.A.toggle_display_inline);
$A.addClass(tag_element, this.A.toggle_tag_active);
if (this.A.prev_page_el && (tag_element.id !== this.A.prev_tag_el.id)) {
$A.addClass(this.A.prev_page_el, this.A.toggle_display_none);
$A.addClass(this.A.prev_tag_el, this.A.toggle_tag_lazy);
}
this.A.prev_page_el = page_element;
this.A.prev_tag_el = tag_element;
$A.log(page_element);
},
// insert favorite(<div>) given user input
insertFavorite: function (obj_fav) {
var tag_id = this.A.ns_tag + obj_fav.tag,
div_el,
html_string = this.composeFavorite(obj_fav),
page_el = $A.el('#' + tag_id + '_page');
div_el = $A.HTMLToElement(html_string);
if (!page_el) {
page_el = this.insertTagAndPage(tag_id);
}
$A.eachChild(page_el, function (iter) {
if (iter === null) {
page_el.appendChild(div_el);
return true;
}
if (div_el.id < iter.id) {
page_el.insertBefore(div_el, iter);
return true;
}
if (iter === page_el.lastChild) {
page_el.appendChild(div_el);
return true;
}
});
this.flip($A.el('#' + tag_id));
return div_el;
},
/******************************************************************************/
// insert page(<div>) | tag(<p>) given a tag id
insertTagAndPage: function (tag) {
var par_el,
div_el,
hold_tags_el,
hold_arcmarks_el,
self = this;
hold_tags_el = this.E.hold_tags;
hold_arcmarks_el = this.E.hold_arcmarks;
par_el = $A.createElement('p');
par_el.innerHTML = tag.slice(this.A.ns_tag.length);
par_el.className = "single_tag";
par_el.id = tag;
// insert the tag(<p>)
$A.eachChild(hold_tags_el, function (iter) {
if (iter === null) {
hold_tags_el.appendChild(par_el);
return true;
}
if (par_el.id < iter.id) {
hold_tags_el.insertBefore(par_el, iter);
return true;
}
if (iter === hold_tags_el.lastChild) {
hold_tags_el.appendChild(par_el);
return true;
}
});
par_el.addEventListener("click", function () {
self.flip(this);
});
div_el = $A.createElement('div');
div_el.className = "bookmark_page";
div_el.id = tag + "_page";
div_el.style.display = "";
// insert the page(<div>);
$A.eachChild(hold_arcmarks_el, function (iter) {
if (iter === null) {
hold_arcmarks_el.appendChild(div_el);
return true;
}
if (div_el.id < iter.id) {
hold_arcmarks_el.insertBefore(div_el, iter);
return true;
}
if (iter === hold_arcmarks_el.lastChild) {
hold_arcmarks_el.appendChild(div_el);
return true;
}
});
return div_el;
},
/******************************************************************************/
// delete a favorite(<div>) given a link
deleteFavorite: function (link_el) {
var self = this,
div_el = link_el.parentNode;
$(div_el).toggle("explode", function () {
if (div_el.previousSibling === null &&
div_el.nextSibling === null) {
self.deleteTagAndPage(div_el);
}
$A.removeElement(div_el);
});
},
/******************************************************************************/
// delete tag(<p>) and page(<div>) given a favorite sub-element
deleteTagAndPage : function (div_el) {
var page_el = div_el.parentNode,
tag_el = $A.el('#' + page_el.id.slice(0, -5)),
hold_el = $A.el("#hold_tags");
$A.removeElement(tag_el);
$A.removeElement(page_el);
$A.eachChild(hold_el, function (iter_el) {
if (iter_el) {
this.flip(iter_el);
return true;
}
}, this);
},
/******************************************************************************/
morph: function (callback) {
var i = 0,
button = this.E.aba_but_del;
if (this.A.but_text === 'Done') {
this.A.but_text = 'Delete';
this.A.class_a = 'bookmark_link';
while (this.E.bookmark_link[i]) {
this.E.bookmark_link[i].removeEventListener("click", callback);
this.E.bookmark_link[i].className = this.A.class_a;
i += 1;
}
button.innerHTML = this.A.but_text;
} else {
this.A.but_text = 'Done';
this.A.class_a = 'bookmark_delete';
while (this.E.bookmark_link[i]) {
this.E.bookmark_link[i].addEventListener("click", callback);
this.E.bookmark_link[i].className = this.A.class_a;
i += 1;
}
button.innerHTML = this.A.but_text;
}
}
}, true);
Related
jQuery widget method not being detected
For the life of me I cannot see the suttle difference between copied code. The _getMiscData method in a child widget apparently doesn't exist according to the parent widget. Can someone explain this? I tried different method names in case I was using a reserved word. I tried private and public method with same result. $(function() { $.widget("custom.textquestion", $.custom.base, { _create: function() { this.element.data("_getControlValue", this.getControlValue()); }, getControlValue: function() { this.element.attr("usersanswer", this.getResponseJSON()); }, _getAnswerSelection: function(answer) { var qname = this._getQuestionName(); var type = this.getType(); return '<div class="radio span6"><label><input type="text" class="answerfield" name="optradio-' + qname + '" value="' + answer.answertext + '"></label></div>' }, _getAnswersDiv: function(answers) { // DIV is required for wrapping around list of answers // so that they can be added all at once. var answerdivs = '<div class="answerlist">' for (k = 0; k < answers.length; k++) { answerdivs += this._getAnswerSelection(answers[k]); } answerdivs += '</div>'; return answerdivs; }, _getPopulatedEditor: function(answers) { var editanswerdiv = ""; for (p = 0; p < answers.length; p++) { editanswerdiv += '<label>Default</label><input type="text" onblur="savequestiondata()" identifier="' + answers[p].answerid + '" name="editanswer' + this._getQuestionName(this.options.questioncontrol) + '" size="20" value="' + answers[p].answertext + '"/><br/>' } return editanswerdiv; }, _getAnswersJSON: function(div) { var answers = []; $(div).find("input[name='editanswer" + this._getQuestionName(this.options.questioncontrol) + "']").each(function(i, u) { var answer = { answerid: $(this).attr('identifier'), answertext: $(this).val(), answerorder: 0, rating: 0 }; answers.push(answer); }); return answers; }, _setAnswerJSON: function(answer) { answer = answer.replace(/['"]+/g, ''); this.options.questioncontrol.find("input[name='optradio-" + this._getQuestionName() + "']").val(answer); return true; }, getResponseJSON: function() { qname = this._getQuestionName(); console.log("The control name is " + qname); var answer = this.options.questioncontrol.find("input[name='optradio-" + qname + "']").val(); console.log("The answer is " + answer); return answer; }, _refresh: function() { qname = this._getQuestionName(this.options.questioncontrol); // Create the divs for the answer block, then // append to this question as the list of answers. var answers = this._getStoredData().data.answers; var answerhtml = this._getAnswersDiv(answers); this.options.questioncontrol.find(".answer-list").html(""); this.options.questioncontrol.find(".answer-list").append(answerhtml); // Get the explanation text and add to control. var explanation = this._getStoredData().data.explanation; this.options.questioncontrol.find(".explanation").text(explanation); // Populate the editor controls with the answers that // are already stored - ready for editing. var editanswerhtml = this._getPopulatedEditor(answers); this.options.questioncontrol.find(".editanswers").html(""); this.options.questioncontrol.find(".editanswers").append(editanswerhtml); this.options.questioncontrol.find(".notes").text(explanation); }, _getQuestionText: function(div) { var qtext; $(div).find("input[name='questiontextedit']").each(function() { qtext = $(this).val(); }); return qtext; }, _getMiscData: function() { var info = [this.options.questioncontrol.find(".email-mask").val()]; return info; }, _setOtherData: function(info) { if (info.emailmask == "true") this.options.questioncontrol.find(".email-mask").attr("checked", "checked"); else this.options.questioncontrol.find(".email-mask").attr("checked", ""); }, _getExplanationText: function(div) { var etext = $(div).find(".notes").val(); return etext; } }); }); $(function() { $.widget("custom.base", { // default options options: { questioncontrol: this, questiondata: null, _storedData: [], }, _create: function() { }, _refresh: function() { }, getEditedAnswers: function(div) { // Get the set of answers that were edited. if (!div) div = this.options.questioncontrol; var answersresult = this._getAnswersJSON(div); var question = this._getQuestionText(div); var typename = this.getType(); var qname = this._getQuestionName(this.options.questioncontrol); var pagenumber = this._getStoredData(qname).data.pagenumber; var order = this._getStoredData(qname).data.order; var explanation = this._getExplanationText(div); var otherdata = this._getMiscData(); var result = { title: question, type: typename, pageid: pagenumber, qname: qname, answers: answersresult, questionorder: order, explanation: explanation, otherdata: otherdata }; return result; }, getType: function() { return $(this.options.questioncontrol).attr('id'); }, setData: function(questiondata) { // Set the title for the question. I.e, the text // for the question. this.options.questioncontrol.find(".questiontitle").text(questiondata.title); this.options.questioncontrol.find("input[name='questiontextedit']").val(questiondata.title); this.options.questioncontrol.find(".notes").text(questiondata.explanation); // Store the data into datastore. var stored = 0; if (this._getStoredData(questiondata.qname) == null) { this.options._storedData.push({ qname: questiondata.qname, data: questiondata }); } else { var datastored = this._getStoredData(questiondata.qname); datastored.data = questiondata; } if (questiondata.otherdata) this._setOtherData(questiondata.otherdata); this._refresh(); }, setAnswer: function(answer) { this._setAnswerJSON(answer); }, _getQuestionName: function() { return this.options.questioncontrol.find('.questionname').val(); }, _getStoredData: function() { var qname = this._getQuestionName(this.options.questioncontrol); for (p = 0; p < this.options._storedData.length; p++) { if (this.options._storedData[p].qname == qname) return this.options._storedData[p]; } return null; }, }); }); The custom.base widget shouldn't return with "this.getMiscData is not a function"
How can I delete Items from json string without using $.grep
I have a cart variable and I am storing the cart inside it like this. [{"course_id":"24","doc_id":"211","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"217","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"218","doc_title":"PDF Solved Past Papers","doc_price":"500"},{"course_id":"26","doc_id":"224","doc_title":"PDF Solved Past Papers","doc_price":"595"}] I created a RemoveFromCart function. It works in simple JQUERY But it is not working in Framework 7 because of $.grep. Is there any other way I can do it without using $.grep? This is my Function function removeFromCart(course_id, doc_id) { var x = confirm("Are you sure you want to remove this item from your cart?"); if (x) { $$('#cart_body').html(''); existing_cart = localStorage.getItem("cart"); if (existing_cart == '') { existing_cart = []; } else { existing_cart = JSON.parse(existing_cart); } existing_cart = $.grep(existing_cart, function (data, index) { return data.doc_id != doc_id }); ex_cart = JSON.stringify(existing_cart); localStorage.setItem('cart', ex_cart); existing_cart = localStorage.getItem("cart"); if (existing_cart == '') { existing_cart = []; } else { existing_cart = JSON.parse(existing_cart); } if (existing_cart !== null && existing_cart.length > 0) { var total = ''; $$('#cart_div').show(); existing_cart.forEach(function (arrayItem) { var text = ''; text = '<li class="item-content"><div class="item-inner"><div class="item-title">' + arrayItem.doc_title + '</div><div class="item-after">' + arrayItem.course_id + '</div><div class="item-after">' + arrayItem.doc_price + '</div><div class="item-after"><i class="icon icon-cross" onclick="removeFromCart(' + arrayItem.course_id + ',' + arrayItem.doc_id + ')"></i></div></div></li>'; total = Number(total) + Number(arrayItem.doc_price); $$('#cart_body').append(text); }); text = '<tr><td></td><td class="text-center"><b>Total: </b></td><td class="text-center">' + total + '</td><td></td></tr>'; $$('#cart_body').append(text); } else { $$('#cart_div').hide(); text = '<p>Your cart is empty.</p>'; $$('#cart_body').append(text); } } else { return false; } }
Instead of: $.grep(existing_cart, function ... You can use: existing_cart.filter(function ...
var new_courses = existing_cart.map( v=> { if(v.doc_id != doc_id) return v }).filter( v=> {return v}) // new_courses does not contain the course with doc_id map loops through each member of an array. filter removes members not returned in map.
Calling prototype method inside function not working
I am trying to create one gallery class using Javascript and jQuery. I have some prototype function for that gallery class, but when I try to access those functions inside class it shows error. Uncaught TypeError: Gallery.start is not a function My JSfiddle Link Here is my Javascript: /** * * #param options should be object of following * options.images Array of gallery images URL * options.start slide starting point * options.autoPlay This option will be false by default * */ function Gallery(options) { var _this = this; var galleryOptions = options; function randomString(len, charSet) { var ranString = ''; var randomPoz; charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < len; i++) { randomPoz = Math.floor(Math.random() * charSet.length); ranString = ranString + charSet.substring(randomPoz, randomPoz + 1); } return ranString; } function addThumbnail(imgSrc) { return '<li class="thumbnail__list"><img src="' + imgSrc + '" class="thumbnail__list-img" /></li>'; } function renderThumbnail(imgArr) { var html = []; if (imgArr) { $.each(imgArr, function(i, v) { html.push(addThumbnail(v)); }); } return '<ul class="gallery__thumbnail__container">' + html.join('') + '</ul>'; } function getPlaceholder() { return 'dummy.jpg'; } function disableNext(thisObj) { thisObj.galleryElement.find('.next').addClass('disabled'); } function disablePrev(thisObj) { thisObj.galleryElement.find('.prev').addClass('disabled'); } function enableNext(thisObj) { thisObj.galleryElement.find('.next').removeClass('disabled'); } function enablePrev(thisObj) { thisObj.galleryElement.find('.prev').removeClass('disabled'); } function togglePrevNext(self) { if (self._opt.currIndex === (self._opt.imagesLength)) { disableNext(self); } else { enableNext(self); } if ((self._opt.currIndex - 1) === 0) { disablePrev(self); } else { enablePrev(self); } } function controls() { var html = []; html.push('<div class="prev sz-icon-arrow-left"></div>'); html.push('<div class="next sz-icon-arrow-right"></div>'); return '<div class="gallery__controls">' + html.join('') + '</div>'; } function bindClickEvents(galleryElement) { galleryElement.on('click', '.start', function() { _this.start(); }); galleryElement.find('.stop').on('click', function() { _this.stop(); }); galleryElement.find('.prev').on('click', function() { _this.prev(); }); galleryElement.find('.next').on('click', function() { _this.next(); }); galleryElement.find('.thumbnail__list').on('click', function() { _this.goTo(Number($(this).index()) + 1); }); } function checkOptions(option) { var opt = option; opt.images = (opt.images.length) ? opt.images : getPlaceholder(); opt.thumbnail = (opt.thumbnail) ? true : false; opt.fullScreen = (opt.fullScreen) ? true : false; opt.container = (opt.fullScreen) ? 'body' : opt.container; opt.container = (opt.container) ? opt.container : 'body'; opt.autoPlay = (opt.autoPlay) ? true : false; opt.start = (opt.start && opt.start <= Number(opt.images.length)) ? opt.start : 1; return opt; } Gallery.init = function() { var html; _this._opt = checkOptions(galleryOptions); _this._opt.imagesLength = Number(_this._opt.images.length); _this._opt.currIndex = Number(_this._opt.start); _this._opt.elementName = 'gallery--' + randomString(5, 'SZgallery'); if (_this._opt.fullScreen) { html = '<div class="pop-up__model ' + _this._opt.elementName + '">' + '<div class="pop-up__model-table">' + '<div class="pop-up__model-cell">' + '<div class="gallery"><div class="pop-up__model-content">' + '<div class="gallery__inner-wrapper"></div>' + '</div></div>' + '</div></div>' + '</div>'; $(_this._opt.container).append('', html); if (_this._opt.thumbnail) { $('.pop-up__model-content').append('', '<div class="thumbnail__list-wrapper">' + renderThumbnail(options.images) + '</div>').append('', controls()); } } else { $(_this._opt.container).append('', '<div class="gallery gallery--hidden ' + _this._opt.elementName + '"></div>'); } _this.galleryElement = $('.' + _this._opt.elementName); if (_this._opt.fullScreen) { _this.galleryElement.find('.gallery__inner-wrapper').append('', '<div class="gallery__img-holder">' + '<img class="gallery__img-preview" src="' + _this._opt.images[_this._opt.start - 1] + '"/>' + '</div>'); } else { _this.galleryElement.append('', '<div class="gallery__img-holder">' + '<img class="gallery__img-preview" src="' + _this._opt.images[_this._opt.start - 1] + '"/>' + '</div>'); } if (_this._opt.thumbnail) { _this.galleryElement.append('', renderThumbnail(options.images)).append(controls()); } else { _this.galleryElement.append('', controls()); } if (_this._opt.autoPlay) { Gallery.start(); } bindClickEvents(_this.galleryElement); }; Gallery.prototype = { start: function() { _this.goTo(_this._opt.currIndex); _this.galleryElement.removeClass('gallery--hidden'); console.log('started', _this._opt); if (_this._opt.fullScreen) { $('.pop-up__model').addClass('is_visible'); } }, stop: function() { _this.galleryElement.addClass('gallery--hidden'); }, next: function() { if (_this._opt.currIndex <= (_this._opt.imagesLength - 1)) { _this._opt.currIndex++; _this.goTo(_this._opt.currIndex); } }, prev: function() { if ((_this._opt.currIndex - 1) !== 0) { _this._opt.currIndex--; _this.goTo(_this._opt.currIndex); } }, goTo: function(imgNo) { var thumbnail; _this._opt.currIndex = Number(imgNo); if (_this._opt.images[imgNo - 1]) { _this.galleryElement.find('.gallery__img-preview').attr('src', _this._opt.images[imgNo - 1]); } if (_this._opt.thumbnail) { thumbnail = _this.galleryElement.find('.thumbnail__list'); thumbnail.removeClass('active'); thumbnail.eq(imgNo - 1).addClass('active'); } togglePrevNext(_this); }, destroy: function() { console.log('destroyed'); } }; return Gallery; } var imgArr = ['images/placeholder-1.png', 'images/placeholder-2.png', 'images/placeholder-3.jpg', 'images/placeholder-4.jpg']; var hotelPhotosGallery = new Gallery({ images: imgArr, autoPlay: true, container: '.photo-list' }); hotelPhotosGallery.init();
After looking a bit at your code, I found the problem: if (_this._opt.autoPlay) { Gallery.start(); // This method doesn't exist on a non instantiated object } You are trying to call a method on the function itself, not a method on the prototype of an instance of that function (instantiated using new). However, prototype methods won't be available on non-instantiated items because this in a function gets attached to the global object by default. When using new, that this actually becomes a new object and gets implicitly returned from the function, thus creating a new instance. More about using function constructors Generally, this would be fixed by using the context (i.e. this) instead of the function name: if (_this._opt.autoPlay) { this.start(); // Use the context of the instantiated Gallery } In your particular case however, you are re-defining the prototype: Gallery.prototype = { ... } // You are overwriting the prototype object Instead of using the one that the JS engine already prepared for you and add methods on it: // add methods directly on the prototype Gallery.prototype.method1 = // ... Gallery.prototype.method2 = // ... This way is potentially unsafe since it will end up removing anything else that existed in the prototype before you re-defined it. If you are not concerned with this and would like to keep your code the way it is, you can access your method also by explicitly calling the prototype: if (_this._opt.autoPlay) { Gallery.prototype.start(); // Explicitly call the prototype, since you already defined it }
you are not calling it properly. if you need to call prototype function it must be like Gallery.prototype.start() if you are trying to implement a special behavior (object based) then it should be like this. also here are some different ways of simulating the class in JavaScript
SyntaxError: let is a reserved identifier on firefox
I am using those code below 'use strict'; jQuery(document).ready(function($) { function CMB2ConditionalsInit(context) { if(typeof context === 'undefined') { context = 'body'; } $('[data-conditional-id]', context).each(function(i, e) { var $e = $(e), id = $e.data('conditional-id'), value = $e.data('conditional-value'); var $element = $('[name="' + id + '"]'), $parent = $e.parents('.cmb-row:first').hide(); $e.data('conditional-required', $e.prop('required')).prop('required', false); $element .on('change', function(evt){ let conditionValue = CMB2ConditionalsStringToUnicode(evt.currentTarget.value); if(typeof value === 'undefined') { CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"]', ($element.val() ? true : false)); } else { CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"]:not([data-conditional-value="' + conditionValue + '"])', false); CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"][data-conditional-value="' + conditionValue + '"]', true); CMB2ConditionalToggleRows('[data-conditional-id="' + id + '"][data-conditional-value*=\'"' + conditionValue + '"\']', true); } }); if($element.length === 1) { $element.trigger('change'); } else { $element.filter(':checked').trigger('change'); } }); } function CMB2ConditionalsStringToUnicode(string){ let result = '', map = ["Á", "Ă","Ắ","Ặ","Ằ","Ẳ","Ẵ","Ǎ","Â","Ấ","Ậ","Ầ","Ẩ","Ẫ","Ä","Ǟ","Ȧ","Ǡ","Ạ","Ȁ","À","Ả","Ȃ","Ā","Ą","Å","Ǻ","Ḁ","Ⱥ","Ã","Ꜳ","Æ","Ǽ","Ǣ","Ꜵ","Ꜷ","Ꜹ","Ꜻ","Ꜽ","Ḃ","Ḅ","Ɓ","Ḇ","Ƀ","Ƃ","Ć","Č","Ç","Ḉ","Ĉ","Ċ","Ƈ","Ȼ","Ď","Ḑ","Ḓ","Ḋ","Ḍ","Ɗ","Ḏ","Dz","Dž","Đ","Ƌ","DZ","DŽ","É","Ĕ","Ě","Ȩ","Ḝ","Ê","Ế","Ệ","Ề","Ể","Ễ","Ḙ","Ë","Ė","Ẹ","Ȅ","È","Ẻ","Ȇ","Ē","Ḗ","Ḕ","Ę","Ɇ","Ẽ","Ḛ","Ꝫ","Ḟ","Ƒ","Ǵ","Ğ","Ǧ","Ģ","Ĝ","Ġ","Ɠ","Ḡ","Ǥ","Ḫ","Ȟ","Ḩ","Ĥ","Ⱨ","Ḧ","Ḣ","Ḥ","Ħ","Í","Ĭ","Ǐ","Î","Ï","Ḯ","İ","Ị","Ȉ","Ì","Ỉ","Ȋ","Ī","Į","Ɨ","Ĩ","Ḭ","Ꝺ","Ꝼ","Ᵹ","Ꞃ","Ꞅ","Ꞇ","Ꝭ","Ĵ","Ɉ","Ḱ","Ǩ","Ķ","Ⱪ","Ꝃ","Ḳ","Ƙ","Ḵ","Ꝁ","Ꝅ","Ĺ","Ƚ","Ľ","Ļ","Ḽ","Ḷ","Ḹ","Ⱡ","Ꝉ","Ḻ","Ŀ","Ɫ","Lj","Ł","LJ","Ḿ","Ṁ","Ṃ","Ɱ","Ń","Ň","Ņ","Ṋ","Ṅ","Ṇ","Ǹ","Ɲ","Ṉ","Ƞ","Nj","Ñ","NJ","Ó","Ŏ","Ǒ","Ô","Ố","Ộ","Ồ","Ổ","Ỗ","Ö","Ȫ","Ȯ","Ȱ","Ọ","Ő","Ȍ","Ò","Ỏ","Ơ","Ớ","Ợ","Ờ","Ở","Ỡ","Ȏ","Ꝋ","Ꝍ","Ō","Ṓ","Ṑ","Ɵ","Ǫ","Ǭ","Ø","Ǿ","Õ","Ṍ","Ṏ","Ȭ","Ƣ","Ꝏ","Ɛ","Ɔ","Ȣ","Ṕ","Ṗ","Ꝓ","Ƥ","Ꝕ","Ᵽ","Ꝑ","Ꝙ","Ꝗ","Ŕ","Ř","Ŗ","Ṙ","Ṛ","Ṝ","Ȑ","Ȓ","Ṟ","Ɍ","Ɽ","Ꜿ","Ǝ","Ś","Ṥ","Š","Ṧ","Ş","Ŝ","Ș","Ṡ","Ṣ","Ṩ","Ť","Ţ","Ṱ","Ț","Ⱦ","Ṫ","Ṭ","Ƭ","Ṯ","Ʈ","Ŧ","Ɐ","Ꞁ","Ɯ","Ʌ","Ꜩ","Ú","Ŭ","Ǔ","Û","Ṷ","Ü","Ǘ","Ǚ","Ǜ","Ǖ","Ṳ","Ụ","Ű","Ȕ","Ù","Ủ","Ư","Ứ","Ự","Ừ","Ử","Ữ","Ȗ","Ū","Ṻ","Ų","Ů","Ũ","Ṹ","Ṵ","Ꝟ","Ṿ","Ʋ","Ṽ","Ꝡ","Ẃ","Ŵ","Ẅ","Ẇ","Ẉ","Ẁ","Ⱳ","Ẍ","Ẋ","Ý","Ŷ","Ÿ","Ẏ","Ỵ","Ỳ","Ƴ","Ỷ","Ỿ","Ȳ","Ɏ","Ỹ","Ź","Ž","Ẑ","Ⱬ","Ż","Ẓ","Ȥ","Ẕ","Ƶ","IJ","Œ","ᴀ","ᴁ","ʙ","ᴃ","ᴄ","ᴅ","ᴇ","ꜰ","ɢ","ʛ","ʜ","ɪ","ʁ","ᴊ","ᴋ","ʟ","ᴌ","ᴍ","ɴ","ᴏ","ɶ","ᴐ","ᴕ","ᴘ","ʀ","ᴎ","ᴙ","ꜱ","ᴛ","ⱻ","ᴚ","ᴜ","ᴠ","ᴡ","ʏ","ᴢ","á","ă","ắ","ặ","ằ","ẳ","ẵ","ǎ","â","ấ","ậ","ầ","ẩ","ẫ","ä","ǟ","ȧ","ǡ","ạ","ȁ","à","ả","ȃ","ā","ą","ᶏ","ẚ","å","ǻ","ḁ","ⱥ","ã","ꜳ","æ","ǽ","ǣ","ꜵ","ꜷ","ꜹ","ꜻ","ꜽ","ḃ","ḅ","ɓ","ḇ","ᵬ","ᶀ","ƀ","ƃ","ɵ","ć","č","ç","ḉ","ĉ","ɕ","ċ","ƈ","ȼ","ď","ḑ","ḓ","ȡ","ḋ","ḍ","ɗ","ᶑ","ḏ","ᵭ","ᶁ","đ","ɖ","ƌ","ı","ȷ","ɟ","ʄ","dz","dž","é","ĕ","ě","ȩ","ḝ","ê","ế","ệ","ề","ể","ễ","ḙ","ë","ė","ẹ","ȅ","è","ẻ","ȇ","ē","ḗ","ḕ","ⱸ","ę","ᶒ","ɇ","ẽ","ḛ","ꝫ","ḟ","ƒ","ᵮ","ᶂ","ǵ","ğ","ǧ","ģ","ĝ","ġ","ɠ","ḡ","ᶃ","ǥ","ḫ","ȟ","ḩ","ĥ","ⱨ","ḧ","ḣ","ḥ","ɦ","ẖ","ħ","ƕ","í","ĭ","ǐ","î","ï","ḯ","ị","ȉ","ì","ỉ","ȋ","ī","į","ᶖ","ɨ","ĩ","ḭ","ꝺ","ꝼ","ᵹ","ꞃ","ꞅ","ꞇ","ꝭ","ǰ","ĵ","ʝ","ɉ","ḱ","ǩ","ķ","ⱪ","ꝃ","ḳ","ƙ","ḵ","ᶄ","ꝁ","ꝅ","ĺ","ƚ","ɬ","ľ","ļ","ḽ","ȴ","ḷ","ḹ","ⱡ","ꝉ","ḻ","ŀ","ɫ","ᶅ","ɭ","ł","lj","ſ","ẜ","ẛ","ẝ","ḿ","ṁ","ṃ","ɱ","ᵯ","ᶆ","ń","ň","ņ","ṋ","ȵ","ṅ","ṇ","ǹ","ɲ","ṉ","ƞ","ᵰ","ᶇ","ɳ","ñ","nj","ó","ŏ","ǒ","ô","ố","ộ","ồ","ổ","ỗ","ö","ȫ","ȯ","ȱ","ọ","ő","ȍ","ò","ỏ","ơ","ớ","ợ","ờ","ở","ỡ","ȏ","ꝋ","ꝍ","ⱺ","ō","ṓ","ṑ","ǫ","ǭ","ø","ǿ","õ","ṍ","ṏ","ȭ","ƣ","ꝏ","ɛ","ᶓ","ɔ","ᶗ","ȣ","ṕ","ṗ","ꝓ","ƥ","ᵱ","ᶈ","ꝕ","ᵽ","ꝑ","ꝙ","ʠ","ɋ","ꝗ","ŕ","ř","ŗ","ṙ","ṛ","ṝ","ȑ","ɾ","ᵳ","ȓ","ṟ","ɼ","ᵲ","ᶉ","ɍ","ɽ","ↄ","ꜿ","ɘ","ɿ","ś","ṥ","š","ṧ","ş","ŝ","ș","ṡ","ṣ","ṩ","ʂ","ᵴ","ᶊ","ȿ","ɡ","ᴑ","ᴓ","ᴝ","ť","ţ","ṱ","ț","ȶ","ẗ","ⱦ","ṫ","ṭ","ƭ","ṯ","ᵵ","ƫ","ʈ","ŧ","ᵺ","ɐ","ᴂ","ǝ","ᵷ","ɥ","ʮ","ʯ","ᴉ","ʞ","ꞁ","ɯ","ɰ","ᴔ","ɹ","ɻ","ɺ","ⱹ","ʇ","ʌ","ʍ","ʎ","ꜩ","ú","ŭ","ǔ","û","ṷ","ü","ǘ","ǚ","ǜ","ǖ","ṳ","ụ","ű","ȕ","ù","ủ","ư","ứ","ự","ừ","ử","ữ","ȗ","ū","ṻ","ų","ᶙ","ů","ũ","ṹ","ṵ","ᵫ","ꝸ","ⱴ","ꝟ","ṿ","ʋ","ᶌ","ⱱ","ṽ","ꝡ","ẃ","ŵ","ẅ","ẇ","ẉ","ẁ","ⱳ","ẘ","ẍ","ẋ","ᶍ","ý","ŷ","ÿ","ẏ","ỵ","ỳ","ƴ","ỷ","ỿ","ȳ","ẙ","ɏ","ỹ","ź","ž","ẑ","ʑ","ⱬ","ż","ẓ","ȥ","ẕ","ᵶ","ᶎ","ʐ","ƶ","ɀ","ff","ffi","ffl","fi","fl","ij","œ","st","ₐ","ₑ","ᵢ","ⱼ","ₒ","ᵣ","ᵤ","ᵥ","ₓ"]; for(let i = 0; i < string.length; i++){ if(jQuery.inArray(string[i], map) === -1) { result += string[i] } else { result += "\\\\u" + ("000" + string[i].charCodeAt(0).toString(16)).substr(-4); } } return result; }; function CMB2ConditionalToggleRows(obj, showOrHide){ var $elements = (obj instanceof jQuery) ? obj : $(obj); return $elements.each(function(i, e) { let $e = $(e); $e.prop('required', showOrHide && $e.data('conditional-required')); $e.parents('.cmb-row:first').toggle(showOrHide); }); } CMB2ConditionalsInit('#post'); }); But it is giving me error below After searched stackoverflow, I got that it will not work on firefox. Is there any way to fix it? BTW, other browser working fine. Thanks in advance.
As you can see the let keyword isn't supported on FF yet: https://kangax.github.io/compat-table/es6/ You will need to change it to var, or transpile your code with babel
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.