Perfomance issues with large number of elements in Mithril.js - javascript

My app has a sort- and filterable list and a few inputs and checkboxes so far.
The problem appears if the list has more than 500 items, then every every element with user input (checkboxes, input fields, menus) start to have a lag around half a second increasing with the number of items in the list. The sorting and filtering of the list is done fast enough but the lag on the input elements is too long.
The question is: how can the list and the input elements be decoupled?
Here is the list code:
var list = {}
list.controller = function(args) {
var model = args.model;
var vm = args.vm;
var vmc = args.vmc;
var appCtrl = args.appCtrl;
this.items = vm.filteredList;
this.onContextMenu = vmc.onContextMenu;
this.isSelected = function(guid) {
return utils.getState(vm.listState, guid, "isSelected");
}
this.setSelected = function(guid) {
utils.setState(vm.listState, guid, "isSelected", true);
}
this.toggleSelected = function(guid) {
utils.toggleState(vm.listState, guid, "isSelected");
}
this.selectAll = function() {
utils.setStateBatch(vm.listState, "GUID", "isSelected", true, this.items());
}.bind(this);
this.deselectAll = function() {
utils.setStateBatch(vm.listState, "GUID", "isSelected", false, this.items());
}.bind(this);
this.invertSelection = function() {
utils.toggleStateBatch(vm.listState, "GUID", "isSelected", this.items());
}.bind(this);
this.id = "201505062224";
this.contextMenuId = "201505062225";
this.initRow = function(item, idx) {
if (item.online) {
return {
id : item.guid,
filePath : (item.FilePath + item.FileName).replace(/\\/g, "\\\\"),
class : idx % 2 !== 0 ? "online odd" : "online even",
}
} else {
return {
class : idx % 2 !== 0 ? "odd" : "even"
}
}
};
// sort helper function
this.sorts = function(list) {
return {
onclick : function(e) {
var prop = e.target.getAttribute("data-sort-by")
//console.log("100")
if (prop) {
var first = list[0]
if(prop === "selection") {
list.sort(function(a, b) {
return this.isSelected(b.GUID) - this.isSelected(a.GUID)
}.bind(this));
} else {
list.sort(function(a, b) {
return a[prop] > b[prop] ? 1 : a[prop] < b[prop] ? -1 : 0
})
}
if (first === list[0])
list.reverse()
}
}.bind(this)
}
};
// text inside the table can be selected with the mouse and will be stored for
// later retrieval
this.getSelected = function() {
//console.log(utils.getSelText());
vmc.lastSelectedText(utils.getSelText());
};
};
list.view = function(ctrl) {
var contextMenuSelection = m("div", {
id : ctrl.contextMenuId,
class : "hide"
}, [
m(".menu-item.allow-hover", {
onclick : ctrl.selectAll
}, "Select all"),
m(".menu-item.allow-hover", {
onclick : ctrl.deselectAll
}, "Deselect all"),
m(".menu-item.allow-hover", {
onclick : ctrl.invertSelection
}, "Invert selection") ]);
var table = m("table", ctrl.sorts(ctrl.items()), [
m("tr", [
m("th[data-sort-by=selection]", {
oncontextmenu : ctrl.onContextMenu(ctrl.contextMenuId, "context-menu context-menu-bkg", "hide" )
}, "S"),
m("th[data-sort-by=FileName]", "Name"),
m("th[data-sort-by=FileSize]", "Size"),
m("th[data-sort-by=FilePath]", "Path"),
m("th[data-sort-by=MediumName]", "Media") ]),
ctrl.items().map(function(item, idx) {
return m("tr", ctrl.initRow(item, idx), {
key : item.GUID
},
[ m("td", [m("input[type=checkbox]", {
id : item.GUID,
checked : ctrl.isSelected(item.GUID),
onclick : function(e) {ctrl.toggleSelected(this.id);}
}) ]),
m("td", {
onmouseup: function(e) {ctrl.getSelected();}
}, item.FileName),
m("td", utils.numberWithDots(item.FileSize)),
m("td", item.FilePath),
m("td", item.MediumName) ])
}) ])
return m("div", [contextMenuSelection, table])
}
And this is how the list and all other components are initialized from the apps main view:
// the main view which assembles all components
var mainCompView = function(ctrl, args) {
// TODO do we really need him there?
// add the main controller for this page to the arguments for all
// added components
var myArgs = args;
myArgs.appCtrl = ctrl;
// create all needed components
var filterComp = m.component(filter, myArgs);
var part_filter = m(".row", [ m(".col-md-2", [ filterComp ]) ]);
var listComp = m.component(list, myArgs);
var part_list = m(".col-md-10", [ listComp ]);
var optionsComp = m.component(options, myArgs);
var part_options = m(".col-md-10", [ optionsComp ]);
var menuComp = m.component(menu, myArgs);
var part_menu = m(".menu-0", [ menuComp ]);
var outputComp = m.component(output, myArgs);
var part_output = m(".col-md-10", [ outputComp ]);
var part1 = m("[id='1']", {
class : 'optionsContainer'
}, "", [ part_options ]);
var part2 = m("[id='2']", {
class : 'menuContainer'
}, "", [ part_menu ]);
var part3 = m("[id='3']", {
class : 'commandContainer'
}, "", [ part_filter ]);
var part4 = m("[id='4']", {
class : 'outputContainer'
}, "", [ part_output ]);
var part5 = m("[id='5']", {
class : 'listContainer'
}, "", [ part_list ]);
return [ part1, part2, part3, part4, part5 ];
}
// run
m.mount(document.body, m.component({
controller : MainCompCtrl,
view : mainCompView
}, {
model : modelMain,
vm : modelMain.getVM(),
vmc : viewModelCommon
}));
I started to workaround the problem by adding m.redraw.strategy("none") and m.startComputation/endComputation to click events and this solves the problem but is this the right solution? As an example, if I use a Mithril component from a 3rd party together with my list component, how should I do this for the foreign component without changing its code?
On the other side, could my list component use something like the 'retain' flag? So the list doesn't redraw by default unless it's told to do? But also the problem with a 3rd party component would persist.
I know there are other strategies to solve this problem like pagination for the list but I would like to know what are best practices from the Mithril side.
Thanks in advance,
Stefan

Thanks to the comment from Barney I found a solution: Occlusion culling. The original example can be found here http://jsfiddle.net/7JNUy/1/ .
I adapted the code for my needs, especially there was the need to throttle the scroll events fired so the number of redraws are good enough for smooth scrolling. Look at the function obj.onScroll.
var list = {}
list.controller = function(args) {
var obj = {};
var model = args.model;
var vm = args.vm;
var vmc = args.vmc;
var appCtrl = args.appCtrl;
obj.vm = vm;
obj.items = vm.filteredList;
obj.onContextMenu = vmc.onContextMenu;
obj.isSelected = function(guid) {
return utils.getState(vm.listState, guid, "isSelected");
}
obj.setSelected = function(guid) {
utils.setState(vm.listState, guid, "isSelected", true);
}
obj.toggleSelected = function(guid) {
utils.toggleState(vm.listState, guid, "isSelected");
m.redraw.strategy("none");
}
obj.selectAll = function() {
utils.setStateBatch(vm.listState, "GUID", "isSelected", true, obj.items());
};
obj.deselectAll = function() {
utils.setStateBatch(vm.listState, "GUID", "isSelected", false, obj.items());
};
obj.invertSelection = function() {
utils.toggleStateBatch(vm.listState, "GUID", "isSelected", obj.items());
};
obj.id = "201505062224";
obj.contextMenuId = "201505062225";
obj.initRow = function(item, idx) {
if (item.online) {
return {
id : item.GUID,
filePath : (item.FilePath + item.FileName).replace(/\\/g, "\\\\"),
class : idx % 2 !== 0 ? "online odd" : "online even",
onclick: console.log(item.GUID)
}
} else {
return {
id : item.GUID,
// class : idx % 2 !== 0 ? "odd" : "even",
onclick: function(e) { obj.selectRow(e, this, item.GUID);
m.redraw.strategy("none");
e.stopPropagation();
}
}
}
};
// sort helper function
obj.sorts = function(list) {
return {
onclick : function(e) {
var prop = e.target.getAttribute("data-sort-by")
// console.log("100")
if (prop) {
var first = list[0]
if(prop === "selection") {
list.sort(function(a, b) {
return obj.isSelected(b.GUID) - obj.isSelected(a.GUID)
});
} else {
list.sort(function(a, b) {
return a[prop] > b[prop] ? 1 : a[prop] < b[prop] ? -1 : 0
})
}
if (first === list[0])
list.reverse()
} else {
e.stopPropagation();
m.redraw.strategy("none");
}
}
}
};
// text inside the table can be selected with the mouse and will be stored
// for
// later retrieval
obj.getSelected = function(e) {
// console.log("getSelected");
var sel = utils.getSelText();
if(sel.length != 0) {
vmc.lastSelectedText(utils.getSelText());
e.stopPropagation();
// console.log("1000");
}
m.redraw.strategy("none");
// console.log("1001");
};
var selectedRow, selectedId;
var eventHandlerAdded = false;
// Row callback; reset the previously selected row and select the new one
obj.selectRow = function (e, row, id) {
console.log("selectRow " + id);
unSelectRow();
selectedRow = row;
selectedId = id;
selectedRow.style.background = "#FDFF47";
if(!eventHandlerAdded) {
console.log("eventListener added");
document.addEventListener("click", keyHandler, false);
document.addEventListener("keypress", keyHandler, false);
eventHandlerAdded = true;
}
};
var unSelectRow = function () {
if (selectedRow !== undefined) {
selectedRow.removeAttribute("style");
selectedRow = undefined;
selectedId = undefined;
}
};
var keyHandler = function(e) {
var num = parseInt(utils.getKeyChar(e), 10);
if(constants.RATING_NUMS.indexOf(num) != -1) {
console.log("number typed: " + num);
// TODO replace with the real table name and the real column name
// $___{<request>res:/tables/catalogItem</request>}
model.newValue("item_update_values", selectedId, {"Rating": num});
m.redraw.strategy("diff");
m.redraw();
} else if((e.keyCode && (e.keyCode === constants.ESCAPE_KEY))
|| e.type === "click") {
console.log("eventListener removed");
document.removeEventListener("click", keyHandler, false);
document.removeEventListener("keypress", keyHandler, false);
eventHandlerAdded = false;
unSelectRow();
}
};
// window seizes for adjusting lists, tables etc
vm.state = {
pageY : 0,
pageHeight : 400
};
vm.scrollWatchUpdateStateId = null;
obj.onScroll = function() {
return function(e) {
console.log("scroll event found");
vm.state.pageY = e.target.scrollTop;
m.redraw.strategy("none");
if (!vm.scrollWatchUpdateStateId) {
vm.scrollWatchUpdateStateId = setTimeout(function() {
// update pages
m.redraw();
vm.scrollWatchUpdateStateId = null;
}, 50);
}
}
};
// clean up on unload
obj.onunload = function() {
delete vm.state;
delete vm.scrollWatchUpdateStateId;
};
return obj;
};
list.view = function(ctrl) {
var pageY = ctrl.vm.state.pageY;
var pageHeight = ctrl.vm.state.pageHeight;
var begin = pageY / 41 | 0
// Add 2 so that the top and bottom of the page are filled with
// next/prev item, not just whitespace if item not in full view
var end = begin + (pageHeight / 41 | 0 + 2)
var offset = pageY % 41
var heightCalc = ctrl.items().length * 41;
var contextMenuSelection = m("div", {
id : ctrl.contextMenuId,
class : "hide"
}, [
m(".menu-item.allow-hover", {
onclick : ctrl.selectAll
}, "Select all"),
m(".menu-item.allow-hover", {
onclick : ctrl.deselectAll
}, "Deselect all"),
m(".menu-item.allow-hover", {
onclick : ctrl.invertSelection
}, "Invert selection") ]);
var header = m("table.listHeader", ctrl.sorts(ctrl.items()), m("tr", [
m("th.select_col[data-sort-by=selection]", {
oncontextmenu : ctrl.onContextMenu(ctrl.contextMenuId, "context-menu context-menu-bkg", "hide" )
}, "S"),
m("th.name_col[data-sort-by=FileName]", "Name"),
${ <request>
# add other column headers as configured
<identifier>active:jsPreprocess</identifier>
<argument name="id">list:table01:header</argument>
</request>
} ]), contextMenuSelection);
var table = m("table", ctrl.items().slice(begin, end).map(function(item, idx) {
return m("tr", ctrl.initRow(item, idx), {
key : item.GUID
},
[ m("td.select_col", [m("input[type=checkbox]", {
id : item.GUID,
checked : ctrl.isSelected(item.GUID),
onclick : function(e) {ctrl.toggleSelected(this.id);}
}) ]),
m("td.nameT_col", {
onmouseup: function(e) {ctrl.getSelected(e);}
}, item.FileName),
${ <request>
# add other columns as configured
<identifier>active:jsPreprocess</identifier>
<argument name="id">list:table01:row</argument>
</request>
} ])
}) );
var table_container = m("div[id=l04]",
{style: {position: "relative", top: pageY + "px"}}, table);
var scrollable = m("div[id=l03]",
{style: {height: heightCalc + "px", position: "relative",
top: -offset + "px"}}, table_container);
var scrollable_container = m("div.scrollableContainer[id=l02]",
{onscroll: ctrl.onScroll()}, scrollable );
var list = m("div[id=l01]", [header, scrollable_container]);
return list;
}
Thanks for the comments!

There are some good examples of when to change redraw strategy in the docs: http://mithril.js.org/mithril.redraw.html#changing-redraw-strategy
But in general, changing redraw strategy is rarely used if the application state is stored somewhere so Mithril can access and calculate the diff without touching DOM. It seems like your data is elsewhere, so could it be that your sorts method is getting expensive to run after a certain size?
You could sort the list only after events that modifies it. Otherwise it will be sorted on every redraw Mithril does, which can be quite often.
m.start/endComputation is useful for 3rd party code, especially if it operates on DOM. If the library stores some state, you should use that for the application state as well, so there aren't any redundant and possibly mismatching data.

Related

Cannot get Datatables editor to initialize

I am working on a page where an xlsx file is uploaded, parsed into an array of objects (each row is an object) and then populated into a Data Table. I want to be able to edit the data in the table before i click another button and send it to the database. Cannot get the editing to work though. I have tried loads of different ways that I found online of initializing the editor but none work for me.
If I get rid of the editor code, a normal Data Table works fine, but as of now I get the error:
Cannot read property Editor of undefuned
Here is the code and how I populate the Data Table
$(function() {
let session = '<?=json_encode($_SESSION)?>';
//console.log(session);
var editor = new $.fn.dataTabe.Editor({
table: '#datatable'
});
var table = $('#datatable').DataTable();
table
.order( [ 3, 'asc' ] ).page.len( 10 )
.draw();
});
let fileIn;
let resultArray;
let finalArray = new Array;
document.getElementById('getFile').addEventListener('click', () => {
fileIn = document.getElementById('my_file_input').files[0];
console.log(fileIn);
parseExcel(fileIn);
setTimeout(() => {
resultArray.forEach((arr) => {
let company = (arr.company) ? arr.company : null;
let category = (arr.category) ? arr.category : null;
let pcs_no = (arr.pcs_no) ? arr.pcs_no : null;
let product_name = (arr.product_name) ? arr.product_name : null;
let min_range_rate = (arr.min_range_rate) ? arr.min_range_rate : null;
let max_range_rate = (arr.max_range_rate) ? arr.max_range_rate : null;
let max_total_rate_per_ha = (arr.max_total_rate_per_ha) ? arr.max_total_rate_per_ha : null;
let measure_unit = (arr.measure_unit) ? arr.measure_unit : null;
let range_notes = (arr.range_notes) ? arr.range_notes : null;
let comment = (arr.comment) ? arr.comment : null;
let crops;
let pack_size;
let chemical;
if(arr.crops) {
if(arr.crops.includes(',')) {
crops = arr.crops.split(',');
} else {
crops = arr.crops;
}
} else {
crops = null;
}
if(arr.pack_size) {
if(arr.pack_size.includes(',')) {
pack_size = arr.pack_size.split(',');
} else {
pack_size = arr.pack_size;
}
} else {
pack_size = null;
}
if(arr.chemical) {
if(arr.chemical.includes(',')) {
chemical = arr.chemical.split(',');
} else {
chemical = arr.chemical;
}
} else {
chemical = null;
}
let data = {
company,
category,
pcs_no,
product_name,
min_range_rate,
max_range_rate,
max_total_rate_per_ha,
measure_unit,
range_notes,
comment,
crops,
pack_size,
chemical
}
finalArray.push(data);
});
finalArray.forEach((arr) => {
table.row.add([
arr.company,
arr.category,
arr.category,
arr.pcs_no,
arr.product_name,
arr.pack_size,
arr.chemical,
arr.min_range_rate,
arr.max_range_rate,
arr.max_total_rate_per_ha,
arr.measure_unit,
arr.range_notes,
arr.crops,
(arr.comment) ? arr.comment.trim() : null
]).draw(false)
});
console.log(finalArray);
}, 3000);
});

Issue with translation of static website

I have a static html5 and css3 website, which I want to translate. Primary language is German, and I want to translate it to English and Russian.
I found a jQuery plugin (translate.js), which does exactly what I need but I have one issue with this plugin.
Everything works perfectly, when I use for example
HTML
<p class="trn">Herzlich Willkommen</p>
jQuery:
$(function() {
var t = {
"Herzlich Willkommen": {
en: "Welcome",
ru: "Добро пожаловать"
}
};
var _t = $('body').translate({
lang: "de",
t: t
});
var str = _t.g("translate");
console.log(str);
$(".lang_selector").click(function(ev) {
var lang = $(this).attr("data-value");
_t.lang(lang);
console.log(lang);
ev.preventDefault();
});
});
but when I want to use nested trn class inside parent trn class, unfortunately I can not translate it.
For example:
<h2 class="trn">Ihr <span class="trn">Bauunternehmen</span> in <span class="trn">Wien</span></h2>
Can you help me please?
Plugin documentation
jQuery.translate.js
(function($) {
$.fn.translate = function(options) {
var that = this; //a reference to ourselves
var settings = {
css: "trn",
lang: "en"
/*,
t: {
"translate": {
pt: "tradução",
br: "tradução"
}
}
*/
};
settings = $.extend(settings, options || {});
if (settings.css.lastIndexOf(".", 0) !== 0) //doesn't start with '.'
settings.css = "." + settings.css;
var t = settings.t;
//public methods
this.lang = function(l) {
if (l) {
settings.lang = l;
this.translate(settings); //translate everything
}
return settings.lang;
};
this.get = function(index) {
var res = index;
try {
res = t[index][settings.lang];
} catch (err) {
//not found, return index
return index;
}
if (res)
return res;
else
return index;
};
this.g = this.get;
//main
this.find(settings.css).each(function(i) {
var $this = $(this);
var trn_key = $this.attr("data-trn-key");
if (!trn_key) {
trn_key = $this.html();
$this.attr("data-trn-key", trn_key); //store key for next time
}
$this.html(that.get(trn_key));
});
return this;
};
})(jQuery);

Vue - infinite scroll doesn't fetch new data when bottom of the page is reached

So, I made a method fetchStories that fetches stories from my API in batches of 10, and the new stories can be fetched once you've scrolled to the bottom of the screen. This is what part of my Vue instance looks like:
var discoveryFeed = new Vue({ // eslint-disable-line no-unused-vars
el: '#discoveryFeed',
data: {
userId: userId,
username: username,
tags: [],
selectedTag: null,
stories: [],
checklist: [],
limit: 10,
page: 1,
isEnd: false,
busy: false,
isFollowing: true
},
beforeMount: function() {
var self = this;
self.$http.get('/api/tags')
.then(function(res) {
self.tags = res.body;
}, function(err) {
self.tags = [];
});
self.$http.get('/api/user/' + self.username + '/checklist')
.then(function(res) {
self.checklist = res.body || [];
}, function(err) {
self.checklist = [];
});
self.fetchStories();
},
methods: {
fetchStories: function(isNew) {
var self = this;
isNew = Boolean(isNew);
if(self.isEnd) { return; }
self.busy = true;
var url = '/api/discover';
if(self.selectedTag) {
url = `/api/tags/${self.selectedTag.code}/stories`;
}
url += '?p=' + self.page;
url += '&l=' + self.limit;
self.page += 1;
self.$http.get(url)
.then(function(res) {
self.busy = false;
if(res.body.length === 0) {
self.isEnd = true;
return;
}
if(isNew) {
self.stories = [];
}
self.stories = self.stories.concat(res.body);
}, function(err) {
self.busy = false;
self.stories = [];
});
},
setTag: function(tag) {
var self = this;
self.selectedTag = tag;
for(var i = 0; i < self.tags.length; i++) {
self.tags[i].selected = false;
}
self.selectedTag.selected = true;
self.page = 1;
self.fetchStories(true);
}
In my pug, I'm using the v-infinite-scroll directive to call the method fetchStories. Also note that I'm working with a list of tags, and clicking a new tag will load different sets of stories through the method setTag(tag).
nav.col-lg-3.col-md-4.d-none.d-md-block.d-lg-block.bg-sidebar(v-cloak)
.feed-sidebar.feed-sidebar-interests.border-top-0.border-bottom-0.border-left-0.position-sticky
strong Your Interests
div.list-group.list-unstyled.mt-2(v-if="tags.length > 0")
a.tag-btn.mb-2.align-middle.text-black(v-for="tag, index in tags" v-bind:class="{ active: selectedTag && selectedTag.id === tag.id }" #click="setTag(tag); scrollToTop();")
i.fa-fw.mr-2(v-bind:class="tag.icon + ' fa-lg'"
v-bind:style="'color:' + tag.hexColor")
span {{ tag.name }}
.col-lg-6.col-md-8(v-cloak
v-infinite-scroll="fetchStories"
infinite-scroll-disabled="busy"
infinite-scroll-distance="50")
Upon checking the data response at the initial load, the ten stories are fetched at /stories?p=1&l=10. However, upon reaching the bottom the data response array of /stories?p=2&l=10 is empty. This may have something to do with my use of booleans to set flags when choosing a tag.
Apparently, I should have reset the value of isEnd when I'm setting the new tag.
setTag: function(tag) {
var self = this;
self.selectedTag = tag;
for(var i = 0; i < self.tags.length; i++) {
self.tags[i].selected = false;
}
self.selectedTag.selected = true;
self.page = 1;
self.isEnd = false;
self.fetchStories(true);
}

Explain the difference between var and function.varName in Javascript

I am working the this code and would like to know the difference between
var Point = Geometry.Point and
GelImageLaneViewer.viewers = []
Under what circumstances would I choose to define a var inside a function versus a function.varName?
Code snippet follows from working code :
var GelImageLaneViewer = (function() {
"use strict";
var Point = Geometry.Point,
**Rect = Geometry.Rect**,
harmony = false,
isGel1D = false,
states = {
"identified" : {
"label" : "Identified",
"visible" : true
},
"notAnalyzed" : {
"label" : "Not Analyzed"
}
};
function GelImageLaneViewer(elem) {
var spotToolbar,
svgBox,
spotToolbarBox,
oldViewBox,
newHeight;
ImageViewer.prototype.setViewportPosition('107px', '5px');
ImageViewer.prototype.setRegionsOfInterest($('.gel1d').attr('data-all-regionsofinterest'));
ImageViewer.call(this, elem);
if($('.gel1d').attr('class') === 'hsppImageViewer gel1d') {
isGel1D = true;
}
this.states = {};
svgBox = this.svg.getBoundingClientRect();
this.svg.setAttribute(
"height",
svgBox.height + 'px'
);
**oldViewBox = Rect.fromViewBox(this.svg);**
this.svg.setAttribute(
"viewBox",
[oldViewBox.x, oldViewBox.y, oldViewBox.width, svgBox.height].join(' ')
);
this.image.setAttribute('height', svgBox.height);
}
GelImageLaneViewer.prototype = Object.create(ImageViewer.prototype);
GelImageLaneViewer.prototype.constructor = ImageViewer.constructor;
**GelImageLaneViewer.viewers = [];**
GelImageLaneViewer.noConflict = function () {
harmony = true;
}
window.addEventListener("DOMContentLoaded", function () {
var images = document.querySelectorAll('.hsppImageViewer'),
stop = images.length,
i,
viewer,
src;
if (!harmony) {
for (i = 0; i < stop; i += 1) {
viewer = new GelImageLaneViewer(images[i]);
src = images[i].getAttribute('data-src');
if (!!src) {
viewer.loadURI(src);
}
viewer.initDraw();
**GelImageLaneViewer.viewers.push(viewer);**
}
}
}, false);
return GelImageLaneViewer;
}());
GelImageLaneViewer.viewers will add a property which can be accessed by anything with access to GelImageLaneViewer by asking for GelImageLaneViewer.viewers. Var viewers would create a property which can only be accessed inside the scope of GelImageLaneViewer itself, and wouldn't be visible to anything outside the scope.

Call .js file in UpdatePanel from CodeBehind

I am have been trying to teach myself ASP.NET and Javascript for a project and have been stuck on one problem for literally dozens of hours now.
I found a really nice javascript drag-and-drop list online, copied the source offered and split the css into a .css file, the javascript into a .js file and the HTML and reference into my asp.net page. It worked perfectly. Great!
Next, I replaced the javascript list with a static HTML list populated with the same data, wrapped it in an UpdatePanel and set up an "edit order" button to swap the static list's HTML for the javascript list's HTML when the button is pressed.
No Dice!
First, the initial runtime would throw up javascript errors explaining that certain objects could not be found. For example:
Microsoft JScript runtime error: Unable to get value of the property 'getElementsByTagName': object is null or undefined
Understood, because the elements aren't actually there yet. So I removed my reference to the .js in the main header and tried to register the .js file when the update panel is changed instead.
This is my problem.
Most explanations online have focused onRegisterClientScriptBlock, or RegisterStartupScript, or RegisterClientScriptInclude, or myLiteral and I can't get any of them to work. I also find that lots of online explanations are for running a single javascript function, whereas the script I am trying to get working has 700 lines-worth of them! Do I have to reference them all individually?
Sorry for the, no doubt, newbish question. I waited to ask until I had shouted at the screen with sufficient vitriol to warrant begging for help!
Thanks and regards.
EDIT: CODE
As Requested, this is the code:
VB.net (this is in a sub called by the button press. This is when I need to register my script)
Dim script As String = ""
Dim Labelb As Label = CType(FindControl("Labelb"), Label)
Dim con As SqlConnection
Dim cmd As SqlCommand
con = New SqlConnection("[connection string here]")
con.Open()
Dim lrd As SqlDataReader
cmd = New SqlCommand("[command string here]", con)
lrd = cmd.ExecuteReader
Dim item = ""
While lrd.Read()
item = item & "<li style=""position: relative;"">" & lrd(1) & "</li>"
End While
lrd.Close()
item = "<table id=""phonetics""><tbody><tr><td><ul id=""phonetic3"" class=""boxy"">" & item & "</ul></td></tr></tbody></table><br/>"
Labelb.Text = item
This is the HTML update panel in the asp.net master page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Labelb" runat="server" Text="" />
</ContentTemplate>
</asp:UpdatePanel>
and finally, this is the .js file that I need to register
var ToolMan = {
events : function() {
if (!ToolMan._eventsFactory) throw "ToolMan Events module isn't loaded";
return ToolMan._eventsFactory
},
css : function() {
if (!ToolMan._cssFactory) throw "ToolMan CSS module isn't loaded";
return ToolMan._cssFactory
},
coordinates : function() {
if (!ToolMan._coordinatesFactory) throw "ToolMan Coordinates module isn't loaded";
return ToolMan._coordinatesFactory
},
drag : function() {
if (!ToolMan._dragFactory) throw "ToolMan Drag module isn't loaded";
return ToolMan._dragFactory
},
dragsort : function() {
if (!ToolMan._dragsortFactory) throw "ToolMan DragSort module isn't loaded";
return ToolMan._dragsortFactory
},
helpers : function() {
return ToolMan._helpers
},
cookies : function() {
if (!ToolMan._cookieOven) throw "ToolMan Cookie module isn't loaded";
return ToolMan._cookieOven
},
junkdrawer : function() {
return ToolMan._junkdrawer
}
}
ToolMan._helpers = {
map : function(array, func) {
for (var i = 0, n = array.length; i < n; i++) func(array[i])
},
nextItem : function(item, nodeName) {
if (item == null) return
var next = item.nextSibling
while (next != null) {
if (next.nodeName == nodeName) return next
next = next.nextSibling
}
return null
},
previousItem : function(item, nodeName) {
var previous = item.previousSibling
while (previous != null) {
if (previous.nodeName == nodeName) return previous
previous = previous.previousSibling
}
return null
},
moveBefore : function(item1, item2) {
var parent = item1.parentNode
parent.removeChild(item1)
parent.insertBefore(item1, item2)
},
moveAfter : function(item1, item2) {
var parent = item1.parentNode
parent.removeChild(item1)
parent.insertBefore(item1, item2 ? item2.nextSibling : null)
}
}
/**
* scripts without a proper home
*
* stuff here is subject to change unapologetically and without warning
*/
ToolMan._junkdrawer = {
serializeList : function(list) {
var items = list.getElementsByTagName("li")
var array = new Array()
for (var i = 0, n = items.length; i < n; i++) {
var item = items[i]
array.push(ToolMan.junkdrawer()._identifier(item))
}
return array.join('|')
},
inspectListOrder : function(id) {
alert(ToolMan.junkdrawer().serializeList(document.getElementById(id)))
},
restoreListOrder : function(listID) {
var list = document.getElementById(listID)
if (list == null) return
var cookie = ToolMan.cookies().get("list-" + listID)
if (!cookie) return;
var IDs = cookie.split('|')
var items = ToolMan.junkdrawer()._itemsByID(list)
for (var i = 0, n = IDs.length; i < n; i++) {
var itemID = IDs[i]
if (itemID in items) {
var item = items[itemID]
list.removeChild(item)
list.insertBefore(item, null)
}
}
},
_identifier : function(item) {
var trim = ToolMan.junkdrawer().trim
var identifier
identifier = trim(item.getAttribute("id"))
if (identifier != null && identifier.length > 0) return identifier;
identifier = trim(item.getAttribute("itemID"))
if (identifier != null && identifier.length > 0) return identifier;
// FIXME: strip out special chars or make this an MD5 hash or something
return trim(item.innerHTML)
},
_itemsByID : function(list) {
var array = new Array()
var items = list.getElementsByTagName('li')
for (var i = 0, n = items.length; i < n; i++) {
var item = items[i]
array[ToolMan.junkdrawer()._identifier(item)] = item
}
return array
},
trim : function(text) {
if (text == null) return null
return text.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2')
}
}
ToolMan._eventsFactory = {
fix : function(event) {
if (!event) event = window.event
if (event.target) {
if (event.target.nodeType == 3) event.target = event.target.parentNode
} else if (event.srcElement) {
event.target = event.srcElement
}
return event
},
register : function(element, type, func) {
if (element.addEventListener) {
element.addEventListener(type, func, false)
} else if (element.attachEvent) {
if (!element._listeners) element._listeners = new Array()
if (!element._listeners[type]) element._listeners[type] = new Array()
var workaroundFunc = function() {
func.apply(element, new Array())
}
element._listeners[type][func] = workaroundFunc
element.attachEvent('on' + type, workaroundFunc)
}
},
unregister : function(element, type, func) {
if (element.removeEventListener) {
element.removeEventListener(type, func, false)
} else if (element.detachEvent) {
if (element._listeners
&& element._listeners[type]
&& element._listeners[type][func]) {
element.detachEvent('on' + type,
element._listeners[type][func])
}
}
}
}
ToolMan._cssFactory = {
readStyle : function(element, property) {
if (element.style[property]) {
return element.style[property]
} else if (element.currentStyle) {
return element.currentStyle[property]
} else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(element, null)
return style.getPropertyValue(property)
} else {
return null
}
}
}
/* FIXME: assumes position styles are specified in 'px' */
ToolMan._coordinatesFactory = {
create : function(x, y) {
// FIXME: Safari won't parse 'throw' and aborts trying to do anything with this file
//if (isNaN(x) || isNaN(y)) throw "invalid x,y: " + x + "," + y
return new _ToolManCoordinate(this, x, y)
},
origin : function() {
return this.create(0, 0)
},
/*
* FIXME: Safari 1.2, returns (0,0) on absolutely positioned elements
*/
topLeftPosition : function(element) {
var left = parseInt(ToolMan.css().readStyle(element, "left"))
var left = isNaN(left) ? 0 : left
var top = parseInt(ToolMan.css().readStyle(element, "top"))
var top = isNaN(top) ? 0 : top
return this.create(left, top)
},
bottomRightPosition : function(element) {
return this.topLeftPosition(element).plus(this._size(element))
},
topLeftOffset : function(element) {
var offset = this._offset(element)
var parent = element.offsetParent
while (parent) {
offset = offset.plus(this._offset(parent))
parent = parent.offsetParent
}
return offset
},
bottomRightOffset : function(element) {
return this.topLeftOffset(element).plus(
this.create(element.offsetWidth, element.offsetHeight))
},
scrollOffset : function() {
if (window.pageXOffset) {
return this.create(window.pageXOffset, window.pageYOffset)
} else if (document.documentElement) {
return this.create(
document.body.scrollLeft + document.documentElement.scrollLeft,
document.body.scrollTop + document.documentElement.scrollTop)
} else if (document.body.scrollLeft >= 0) {
return this.create(document.body.scrollLeft, document.body.scrollTop)
} else {
return this.create(0, 0)
}
},
clientSize : function() {
if (window.innerHeight >= 0) {
return this.create(window.innerWidth, window.innerHeight)
} else if (document.documentElement) {
return this.create(document.documentElement.clientWidth,
document.documentElement.clientHeight)
} else if (document.body.clientHeight >= 0) {
return this.create(document.body.clientWidth,
document.body.clientHeight)
} else {
return this.create(0, 0)
}
},
/**
* mouse coordinate relative to the window (technically the
* browser client area) i.e. the part showing your page
*
* NOTE: in Safari the coordinate is relative to the document
*/
mousePosition : function(event) {
event = ToolMan.events().fix(event)
return this.create(event.clientX, event.clientY)
},
/**
* mouse coordinate relative to the document
*/
mouseOffset : function(event) {
event = ToolMan.events().fix(event)
if (event.pageX >= 0 || event.pageX < 0) {
return this.create(event.pageX, event.pageY)
} else if (event.clientX >= 0 || event.clientX < 0) {
return this.mousePosition(event).plus(this.scrollOffset())
}
},
_size : function(element) {
/* TODO: move to a Dimension class */
return this.create(element.offsetWidth, element.offsetHeight)
},
_offset : function(element) {
return this.create(element.offsetLeft, element.offsetTop)
}
}
function _ToolManCoordinate(factory, x, y) {
this.factory = factory
this.x = isNaN(x) ? 0 : x
this.y = isNaN(y) ? 0 : y
}
_ToolManCoordinate.prototype = {
toString : function() {
return "(" + this.x + "," + this.y + ")"
},
plus : function(that) {
return this.factory.create(this.x + that.x, this.y + that.y)
},
minus : function(that) {
return this.factory.create(this.x - that.x, this.y - that.y)
},
min : function(that) {
return this.factory.create(
Math.min(this.x , that.x), Math.min(this.y , that.y))
},
max : function(that) {
return this.factory.create(
Math.max(this.x , that.x), Math.max(this.y , that.y))
},
constrainTo : function (one, two) {
var min = one.min(two)
var max = one.max(two)
return this.max(min).min(max)
},
distance : function (that) {
return Math.sqrt(Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2))
},
reposition : function(element) {
element.style["top"] = this.y + "px"
element.style["left"] = this.x + "px"
}
}
ToolMan._dragFactory = {
createSimpleGroup : function(element, handle) {
handle = handle ? handle : element
var group = this.createGroup(element)
group.setHandle(handle)
group.transparentDrag()
group.onTopWhileDragging()
return group
},
createGroup : function(element) {
var group = new _ToolManDragGroup(this, element)
var position = ToolMan.css().readStyle(element, 'position')
if (position == 'static') {
element.style["position"] = 'relative'
} else if (position == 'absolute') {
/* for Safari 1.2 */
ToolMan.coordinates().topLeftOffset(element).reposition(element)
}
// TODO: only if ToolMan.isDebugging()
group.register('draginit', this._showDragEventStatus)
group.register('dragmove', this._showDragEventStatus)
group.register('dragend', this._showDragEventStatus)
return group
},
_showDragEventStatus : function(dragEvent) {
window.status = dragEvent.toString()
},
constraints : function() {
return this._constraintFactory
},
_createEvent : function(type, event, group) {
return new _ToolManDragEvent(type, event, group)
}
}
function _ToolManDragGroup(factory, element) {
this.factory = factory
this.element = element
this._handle = null
this._thresholdDistance = 0
this._transforms = new Array()
// TODO: refactor into a helper object, move into events.js
this._listeners = new Array()
this._listeners['draginit'] = new Array()
this._listeners['dragstart'] = new Array()
this._listeners['dragmove'] = new Array()
this._listeners['dragend'] = new Array()
}
_ToolManDragGroup.prototype = {
/*
* TODO:
* - unregister(type, func)
* - move custom event listener stuff into Event library
* - keyboard nudging of "selected" group
*/
setHandle : function(handle) {
var events = ToolMan.events()
handle.toolManDragGroup = this
events.register(handle, 'mousedown', this._dragInit)
handle.onmousedown = function() { return false }
if (this.element != handle)
events.unregister(this.element, 'mousedown', this._dragInit)
},
register : function(type, func) {
this._listeners[type].push(func)
},
addTransform : function(transformFunc) {
this._transforms.push(transformFunc)
},
verticalOnly : function() {
this.addTransform(this.factory.constraints().vertical())
},
horizontalOnly : function() {
this.addTransform(this.factory.constraints().horizontal())
},
setThreshold : function(thresholdDistance) {
this._thresholdDistance = thresholdDistance
},
transparentDrag : function(opacity) {
var opacity = typeof(opacity) != "undefined" ? opacity : 0.75;
var originalOpacity = ToolMan.css().readStyle(this.element, "opacity")
this.register('dragstart', function(dragEvent) {
var element = dragEvent.group.element
element.style.opacity = opacity
element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')'
})
this.register('dragend', function(dragEvent) {
var element = dragEvent.group.element
element.style.opacity = originalOpacity
element.style.filter = 'alpha(opacity=100)'
})
},
onTopWhileDragging : function(zIndex) {
var zIndex = typeof(zIndex) != "undefined" ? zIndex : 100000;
var originalZIndex = ToolMan.css().readStyle(this.element, "z-index")
this.register('dragstart', function(dragEvent) {
dragEvent.group.element.style.zIndex = zIndex
})
this.register('dragend', function(dragEvent) {
dragEvent.group.element.style.zIndex = originalZIndex
})
},
_dragInit : function(event) {
event = ToolMan.events().fix(event)
var group = document.toolManDragGroup = this.toolManDragGroup
var dragEvent = group.factory._createEvent('draginit', event, group)
group._isThresholdExceeded = false
group._initialMouseOffset = dragEvent.mouseOffset
group._grabOffset = dragEvent.mouseOffset.minus(dragEvent.topLeftOffset)
ToolMan.events().register(document, 'mousemove', group._drag)
document.onmousemove = function() { return false }
ToolMan.events().register(document, 'mouseup', group._dragEnd)
group._notifyListeners(dragEvent)
},
_drag : function(event) {
event = ToolMan.events().fix(event)
var coordinates = ToolMan.coordinates()
var group = this.toolManDragGroup
if (!group) return
var dragEvent = group.factory._createEvent('dragmove', event, group)
var newTopLeftOffset = dragEvent.mouseOffset.minus(group._grabOffset)
// TODO: replace with DragThreshold object
if (!group._isThresholdExceeded) {
var distance =
dragEvent.mouseOffset.distance(group._initialMouseOffset)
if (distance < group._thresholdDistance) return
group._isThresholdExceeded = true
group._notifyListeners(
group.factory._createEvent('dragstart', event, group))
}
for (i in group._transforms) {
var transform = group._transforms[i]
newTopLeftOffset = transform(newTopLeftOffset, dragEvent)
}
var dragDelta = newTopLeftOffset.minus(dragEvent.topLeftOffset)
var newTopLeftPosition = dragEvent.topLeftPosition.plus(dragDelta)
newTopLeftPosition.reposition(group.element)
dragEvent.transformedMouseOffset = newTopLeftOffset.plus(group._grabOffset)
group._notifyListeners(dragEvent)
var errorDelta = newTopLeftOffset.minus(coordinates.topLeftOffset(group.element))
if (errorDelta.x != 0 || errorDelta.y != 0) {
coordinates.topLeftPosition(group.element).plus(errorDelta).reposition(group.element)
}
},
_dragEnd : function(event) {
event = ToolMan.events().fix(event)
var group = this.toolManDragGroup
var dragEvent = group.factory._createEvent('dragend', event, group)
group._notifyListeners(dragEvent)
this.toolManDragGroup = null
ToolMan.events().unregister(document, 'mousemove', group._drag)
document.onmousemove = null
ToolMan.events().unregister(document, 'mouseup', group._dragEnd)
},
_notifyListeners : function(dragEvent) {
var listeners = this._listeners[dragEvent.type]
for (i in listeners) {
listeners[i](dragEvent)
}
}
}
function _ToolManDragEvent(type, event, group) {
this.type = type
this.group = group
this.mousePosition = ToolMan.coordinates().mousePosition(event)
this.mouseOffset = ToolMan.coordinates().mouseOffset(event)
this.transformedMouseOffset = this.mouseOffset
this.topLeftPosition = ToolMan.coordinates().topLeftPosition(group.element)
this.topLeftOffset = ToolMan.coordinates().topLeftOffset(group.element)
}
_ToolManDragEvent.prototype = {
toString : function() {
return "mouse: " + this.mousePosition + this.mouseOffset + " " +
"xmouse: " + this.transformedMouseOffset + " " +
"left,top: " + this.topLeftPosition + this.topLeftOffset
}
}
ToolMan._dragFactory._constraintFactory = {
vertical : function() {
return function(coordinate, dragEvent) {
var x = dragEvent.topLeftOffset.x
return coordinate.x != x
? coordinate.factory.create(x, coordinate.y)
: coordinate
}
},
horizontal : function() {
return function(coordinate, dragEvent) {
var y = dragEvent.topLeftOffset.y
return coordinate.y != y
? coordinate.factory.create(coordinate.x, y)
: coordinate
}
}
}
ToolMan._dragsortFactory = {
makeSortable : function(item) {
var group = ToolMan.drag().createSimpleGroup(item)
group.register('dragstart', this._onDragStart)
group.register('dragmove', this._onDragMove)
group.register('dragend', this._onDragEnd)
return group
},
/**
* Iterates over a list's items, making them sortable, applying
* optional functions to each item.
*
* example: makeListSortable(myList, myFunc1, myFunc2, ... , myFuncN)
*/
makeListSortable : function(list) {
var helpers = ToolMan.helpers()
var coordinates = ToolMan.coordinates()
var items = list.getElementsByTagName("li")
helpers.map(items, function(item) {
var dragGroup = dragsort.makeSortable(item)
dragGroup.setThreshold(4)
var min, max
dragGroup.addTransform(function(coordinate, dragEvent) {
return coordinate.constrainTo(min, max)
})
dragGroup.register('dragstart', function() {
var items = list.getElementsByTagName("li")
min = max = coordinates.topLeftOffset(items[0])
for (var i = 1, n = items.length; i < n; i++) {
var offset = coordinates.topLeftOffset(items[i])
min = min.min(offset)
max = max.max(offset)
}
})
})
for (var i = 1, n = arguments.length; i < n; i++)
helpers.map(items, arguments[i])
},
_onDragStart : function(dragEvent) {
},
_onDragMove : function(dragEvent) {
var helpers = ToolMan.helpers()
var coordinates = ToolMan.coordinates()
var item = dragEvent.group.element
var xmouse = dragEvent.transformedMouseOffset
var moveTo = null
var previous = helpers.previousItem(item, item.nodeName)
while (previous != null) {
var bottomRight = coordinates.bottomRightOffset(previous)
if (xmouse.y <= bottomRight.y && xmouse.x <= bottomRight.x) {
moveTo = previous
}
previous = helpers.previousItem(previous, item.nodeName)
}
if (moveTo != null) {
helpers.moveBefore(item, moveTo)
return
}
var next = helpers.nextItem(item, item.nodeName)
while (next != null) {
var topLeft = coordinates.topLeftOffset(next)
if (topLeft.y <= xmouse.y && topLeft.x <= xmouse.x) {
moveTo = next
}
next = helpers.nextItem(next, item.nodeName)
}
if (moveTo != null) {
helpers.moveBefore(item, helpers.nextItem(moveTo, item.nodeName))
return
}
},
_onDragEnd : function(dragEvent) {
ToolMan.coordinates().create(0, 0).reposition(dragEvent.group.element)
}
}
ToolMan._cookieOven = {
set : function(name, value, expirationInDays) {
if (expirationInDays) {
var date = new Date()
date.setTime(date.getTime() + (expirationInDays * 24 * 60 * 60 * 1000))
var expires = "; expires=" + date.toGMTString()
} else {
var expires = ""
}
document.cookie = name + "=" + value + expires + "; path=/"
},
get : function(name) {
var namePattern = name + "="
var cookies = document.cookie.split(';')
for(var i = 0, n = cookies.length; i < n; i++) {
var c = cookies[i]
while (c.charAt(0) == ' ') c = c.substring(1, c.length)
if (c.indexOf(namePattern) == 0)
return c.substring(namePattern.length, c.length)
}
return null
},
eraseCookie : function(name) {
createCookie(name, "", -1)
}
}
var dragsort = ToolMan.dragsort()
var junkdrawer = ToolMan.junkdrawer()
window.onload = function() {
junkdrawer.restoreListOrder("phonetic3")
//junkdrawer.restoreListOrder("twolists1")
//junkdrawer.restoreListOrder("twolists2")
dragsort.makeListSortable(document.getElementById("phonetic3"),
verticalOnly, saveOrder)
/*
dragsort.makeListSortable(document.getElementById("twolists1"),
saveOrder)
dragsort.makeListSortable(document.getElementById("twolists2"),
saveOrder)
*/
}
function verticalOnly(item) {
item.toolManDragGroup.verticalOnly()
}
function speak(id, what) {
var element = document.getElementById(id);
element.innerHTML = 'Clicked ' + what;
}
function saveOrder(item) {
var group = item.toolManDragGroup
var list = group.element.parentNode
var id = list.getAttribute("id")
if (id == null) return
group.register('dragend', function() {
ToolMan.cookies().set("list-" + id,
junkdrawer.serializeList(list), 365)
})
}
//-->
Thanks so much for your support!
Regards,
If you are seeing "value of the property 'getElementsByTagName' object is null or undefined" there is one of two possible issues:
1) your script file is not properly loaded.
2) You are calling 'getElementsByTagName' inappropriately.
Since you haven't posted any sample code, it would be very difficult for anybody to provide a definitive answer to your question.

Categories