IndexedDB query to get individual page - javascript

I am trying to load a new page in my IndexedDB application.
I have a list of rooms, and when the user clicks on the next room in the list, it should load that room's details on the page.
Currently it just skips over the itemStore.openCursor().onsuccess = function(event) and goes to the end (I know this because I added breakpoints in Developer Tools).
HTML (added dynamically, which is why there's an onclick attribute)
<li id="124">
<small>2. </small>
FH102
</li>
JS
function getPage(roomId) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
openRequest = window.indexedDB.open("rooms", 1);
openRequest.onupgradeneeded = function() {
var db = openRequest.result;
var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
var index = itemStore.createIndex("rooms", ["room_id"]);
};
openRequest.onerror = function(event) {
console.error(event);
};
openRequest.onsuccess = function (event) {
var db = openRequest.result;
db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's requests
console.error(event.target);
console.log("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
};
var transaction = db.transaction(['rooms'], "readonly");
var itemStore = transaction.objectStore("rooms");
var index = itemStore.index("rooms", ["room_id"]);
console.log('DB opened');
itemStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
alert(cursor);
if(cursor) {
if(cursor.value.room_id == roomId) {
resetForm($('#room-usage'));
/* populate form with data */
$('#room-name').each(function () {
$(this).html(cursor.value.room_name); //page header
});
$('#prevroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) - 1);
});
$('#nextroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) + 1);
});
$('#sequence').each(function () {
$(this).val(parseInt(cursor.value.room_seq));
$.jStorage.set('currentSeqNo', cursor.value.room_seq, { TTL: 28800000 });
});
$('#route_number').each(function () {
$(this).val(parseInt(cursor.value.route_number));
$.jStorage.set('currentRouteNumber', cursor.value.route_number, { TTL: 28800000 });
});
$('#room_name').each(function () {
$(this).val(cursor.value.room_name); //hidden field
$.jStorage.set('currentRoomName', cursor.value.room_name, { TTL: 28800000 });
});
$('#room_id').each(function () {
$(this).val(cursor.value.room_id);
$.jStorage.set('currentRoomId', cursor.value.room_id, { TTL: 28800000 });
});
$('#countslider').each(function () {
$(this).attr('max',parseInt(cursor.value.capacity));
$.jStorage.set('currentCap', cursor.value.capacity, { TTL: 28800000 });
});
$('#rangesettings span').each(function () {
$(this).html(cursor.value.capacity);
});
window.location.assign('/static#/view/'+cursor.value.room_id);
cursor.continue();
} else {
resetForm($('#room-usage'));
}
cursor.continue();
} else {
console.log('Entries all displayed.');
if(!($.jStorage.get('reverseroute', ''))) {
reverseroute = 'asc';
} else {
reverseroute = $.jStorage.get('reverseroute', '');
}
var $list = $('#mylist');
var directionSort = {
asc: function (a, b) {
return parseInt(a.id) < parseInt(b.id) ? -1 : 1;
},
desc: function (a, b) {
return parseInt(a.id) > parseInt(b.id) ? -1 : 1;
}
}
var $items = $list.children();
$list.empty().append($items.sort(directionSort[reverseroute]));
appendHref(reverseroute);
//asyncCallToPouchDb();
}
};
// Close the db when the transaction is done
transaction.oncomplete = function() {
db.close();
};
};
}

It turned out that the above was nearly correct, except that it didn't need cursor.continue(); - instead it needed cursor.advance(1); - which should have been obvious because it is only retrieving one record from IndexedDB.
Here's the revised code. (The reason there's a 1 tacked on the end of the variable names is that I have already run one IndexedDB query on the page and I thought the variable names being the same was a bit risky.)
function getPage(roomId) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
openRequest1 = window.indexedDB.open("rooms", 1);
openRequest1.onupgradeneeded = function() {
var db1 = openRequest1.result;
var itemStore1 = db1.createObjectStore("rooms", {keyPath: "room_id"});
var index1 = itemStore1.createIndex("rooms", ["room_id"]);
};
openRequest1.onerror = function(event) {
console.error(event);
};
openRequest1.onsuccess = function (event) {
var db1 = openRequest1.result;
db1.onerror = function(event) {
// Generic error handler for all errors targeted at this database's requests
console.error(event.target);
console.log("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
};
var transaction1 = db1.transaction(['rooms'], "readonly");
var itemStore1 = transaction1.objectStore("rooms");
var index1 = itemStore1.index("rooms", ["room_id"]);
console.log('DB opened');
//setTimeout(function(){ alert("Hello"); }, 3000);
itemStore1.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cursor.value.room_id == roomId) {
resetForm($('#room-usage'));
/* populate form with data */
$('#room-name').each(function () {
$(this).html(cursor.value.room_name); //page header
});
$('#prevroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) - 1);
});
$('#nextroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) + 1);
});
$('#sequence').each(function () {
$(this).val(parseInt(cursor.value.room_seq));
$.jStorage.set('currentSeqNo', cursor.value.room_seq, { TTL: 28800000 });
});
$('#route_number').each(function () {
$(this).val(parseInt(cursor.value.route_number));
$.jStorage.set('currentRouteNumber', cursor.value.route_number, { TTL: 28800000 });
});
$('#room_name').each(function () {
$(this).val(cursor.value.room_name); //hidden field
$.jStorage.set('currentRoomName', cursor.value.room_name, { TTL: 28800000 });
//alert($.jStorage.get('currentRoomName',''));
});
$('#room_id').each(function () {
$(this).val(cursor.value.room_id);
$.jStorage.set('currentRoomId', cursor.value.room_id, { TTL: 28800000 });
});
$('#countslider').each(function () {
$(this).attr('max',parseInt(cursor.value.room_capacity));
$.jStorage.set('currentCap', cursor.value.room_capacity, { TTL: 28800000 });
});
$('#rangesettings span').each(function () {
$(this).html(cursor.value.room_capacity);
});
window.location.assign('/static#/view/'+cursor.value.room_id);
//cursor.continue();
cursor.advance(1);
} else {
resetForm($('#room-usage'));
}
// cursor.continue();
// cursor.advance(1);
} else {
console.log('Entries all displayed.');
if(!($.jStorage.get('reverseroute', ''))) {
reverseroute = 'asc';
} else {
reverseroute = $.jStorage.get('reverseroute', '');
}
var $list = $('#mylist');
var directionSort = {
asc: function (a, b) {
return parseInt(a.id) < parseInt(b.id) ? -1 : 1;
},
desc: function (a, b) {
return parseInt(a.id) > parseInt(b.id) ? -1 : 1;
}
}
var $items = $list.children();
$list.empty().append($items.sort(directionSort[reverseroute]));
appendHref(reverseroute);
}
};
// Close the db when the transaction is done
transaction1.oncomplete = function() {
db1.close();
};
};
}

Related

Add more values

$.starRating = function(options) {
var defaults = {
onClickCallBack: null,
};
var settings = $.extend({}, defaults, options);
var onClickCallBack = settings.onClickCallBack;
$(".rating-star span").hover(function() {
var hoverValue = parseInt($(this).attr('data-val'));
highlightStars(hoverValue, 'hover');
});
$(".rating-star span").mouseout(function() {
$(".rating-star span").each(function() {
$(this).removeClass("hover");
});
});
$(".rating-star span").click(function() {
if (onClickCallBack != null) {
var rate = parseInt($(this).attr('data-val'));
var id = parseInt($(this).attr('data-id'));
highlightStars(rate, 'clicked');
onClickCallBack(rate, id);
}
});
function highlightStars(count, cssClass) {
var itemValue = 0;
$(".rating-star span").each(function() {
itemValue = parseInt($(this).attr('data-val'));
if (itemValue <= count) {
$(this).addClass(cssClass);
} else {
$(this).removeClass(cssClass);
}
});
}
function highlightRating(rate) {
var roundedRate = Math.round(rate);
highlightStars(roundedRate, 'clicked');
}
return {
highlightRatingStars: function(rate) {
highlightRating(rate);
}
}
}
$(function() {
var starRatingFunction = $.starRating({
onClickCallBack: onRatingStar
});
function onRatingStar(rate, id) {
$("#1_star_input").val(rate);
$("#2_star_input").val(rate);
$("#3_star_input").val(rate);
loadData();
}
});
Hi guys, I have some star rating jquery code, right now I can use one set of stars and retrieve the values but, I want to be able to get values for three different sets of stars. i'm only getting values for #1_star_input and it does the same for the other two.

Webrtc media streaming is working but datachannel closes (doesn't start at all)

I'm trying to start desktop screen streaming from native client to web browser. When i start connection sdp exchange is ok and media streaming starts as it should. But data channel is immidiately fires "close" event. As i understand data channel should be created befoe sdp exchange and i set negotiate to false. So it should automaticly inform other peer about this channel and start data channel. but it's not in my case.
I tried many different ways like setting datachannel with options or peer connection with or without options.
Am i missing something ?
Following is code for initiator from web browser.
var pcConstraints = {};
var servers = {
//iceTransportPolicy: 'relay', // force turn
iceServers:
[
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'stun:stun.stunprotocol.org:3478' },
{ url: 'stun:stun.anyfirewall.com:3478' }
]
};
var offerOptions = {
offerToReceiveAudio: 0,
offerToReceiveVideo: 1,
trickle: false
};
function startStream() {
console.log("startStream...");
remotestream = new RTCPeerConnection(servers, pcConstraints);
if (localstream) {
remotestream.addStream(localstream);
}
// optional data channel
dataChannel = remotestream.createDataChannel('testchannel', {});
setDataChannel(dataChannel);
remotestream.onaddstream = function (e) {
try {
console.log("remote media connection success!");
var vid2 = document.getElementById('vid2');
vid2.srcObject = e.stream;
vid2.onloadedmetadata = function (e) {
vid2.play();
};
var t = setInterval(function () {
if (!remotestream) {
clearInterval(t);
}
else {
Promise.all([
remotestream.getStats(null).then(function (o) {
var rcv = null;
var snd = null;
o.forEach(function (s) {
if ((s.type == "inbound-rtp" && s.mediaType == "video" && !s.isRemote) ||
(s.type == "ssrc" && s.mediaType == "video" && s.id.indexOf("recv") >= 0))
{
rcv = s;
}
else if((s.type == "outbound-rtp" && s.mediaType == "video" && !s.isRemote) ||
(s.type == "ssrc" && s.mediaType == "video" && s.id.indexOf("send") >= 0))
{
snd = s;
}
});
return dumpStat(rcv, snd);
})
]).then(function (s) {
statsdiv.innerHTML = "<small>" + s + "</small>";
});
}
}, 100);
} catch (ex) {
console.log("Failed to connect to remote media!", ex);
socket.close();
}
};
remotestream.onicecandidate = function (event) {
if (event.candidate) {
var ice = parseIce(event.candidate.candidate);
if (ice && ice.component_id == 1 // skip RTCP
//&& ice.type == 'relay' // force turn
&& ice.localIP.indexOf(":") < 0) { // skip IP6
console.log('onicecandidate[local]: ' + event.candidate.candidate);
var obj = JSON.stringify({
"command": "onicecandidate",
"candidate": event.candidate
});
send(obj);
localIce.push(ice);
}
else {
console.log('onicecandidate[local skip]: ' + event.candidate.candidate);
}
}
else {
console.log('onicecandidate: complete.')
if (remoteAnswer) {
// fill empty pairs using last remote ice
//for (var i = 0, lenl = localIce.length; i < lenl; i++) {
// if (i >= remoteIce.length) {
// var c = remoteIce[remoteIce.length - 1];
// var ice = parseIce(c.candidate);
// ice.foundation += i;
// c.candidate = stringifyIce(ice);
// remotestream.addIceCandidate(c);
// }
//}
}
}
};
remotestream.createOffer(function (desc) {
console.log('createOffer: ' + desc.sdp);
remotestream.setLocalDescription(desc, function () {
var obj = JSON.stringify({
"command": "offer",
"desc": desc
});
send(obj);
},
function (errorInformation) {
console.log('setLocalDescription error: ' + errorInformation);
});
},
function (error) {
alert(error);
},
offerOptions);
}
function setDataChannel(dc) {
dc.onerror = function (error) {
alert("DataChannel Error:", error);
};
dc.onmessage = function (event) {
alert("DataChannel Message:", event.data);
};
dc.onopen = function () {
dataChannel.send("Hello World!");
};
dc.onclose = function (error) {
alert("DataChannel is Closed");
alert(error.data)
};
}

TypeError: Cannot create property 'style' on string 'a'

Honestly do not know whats happen, this was working this morning, have not changed a thing but now when i click my button to generate my images I get this error.
Can anyone tell me why and how to fix this please.
Error
test initMock test generate 1
TypeError: Cannot create property 'style' on string 'a'
at i._createCanvasElement (fabric.min.js:2)
at i._createLowerCanvas (fabric.min.js:2)
at i._initStatic (fabric.min.js:2)
at initialize (fabric.min.js:3)
at new i (fabric.min.js:1)
at b.$scope.uploadImage (controller.js:855)
at b.$scope.generate (controller.js:929)
at fn (eval at compile (angular.js:15500), <anonymous>:4:144)
at e (angular.js:27285)
at b.$eval (angular.js:18372)
my functions
$scope.uploadImage = function (where) {
var deferred = $q.defer();
if (where === 'upload') {
var f = document.getElementById('uploadCreative').files[0];
var r = new FileReader();
r.onload = function () {
var image = new Image();
image.src = r.result;
image.onload = function () {
$scope.resize(image.src).then(function (response) {
deferred.resolve(response);
console.log('hehe NO!');
console.log('hehe NO!');
}).catch(function (response) {
})
}
};
r.readAsDataURL(f);
}
if (where === 'local') {
function ax(a, callback) {
callback(localStorage.getItem(a));
}
var loadCanvas = new fabric.Canvas('a');
divHeight = $('.image-builder').height();
if ($scope.format === '1') {
Aratio = 0.67;
} else if ($scope.format === '2') {
Aratio = 0.56;
} else if ($scope.format === '3') {
divHeight = divHeight / 1.5;
Aratio = 2;
} else if ($scope.format === '4') {
Aratio = 0.67;
} else {
Aratio = 1
}
loadCanvas.setHeight(divHeight - 15);
loadCanvas.setWidth((divHeight - 15) * Aratio);
if (localStorage.getItem('backgroundImage') !== 'null') {
background = localStorage.getItem('backgroundImage');
var imgBc = new Image();
imgBc.onload = function () {
// this is syncronous
Iwidth = this.width;
Iheight = this.height;
var f_img = new fabric.Image(imgBc);
loadCanvas.setBackgroundImage(f_img, loadCanvas.renderAll.bind(loadCanvas), {
scaleY: loadCanvas.height / Iheight,
scaleX: loadCanvas.width / Iwidth
});
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
})
});
});
};
imgBc.src = background;
} else {
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
console.log(response);
})
});
});
}
}
return deferred.promise;
};
$scope.generate = function () {
$scope.generating = true;
$scope.generateBtn = 'Generating';
for (i = 0; i < $scope.gallery.length; i++) {
$scope.select[i] = '';
}
$scope.gallery = [];
$scope.checkPhoto = [];
console.log("test generate 1");
$scope.uploadImage($scope.creative).then(function (result) {
console.log("test generate 2");
$scope.generateCanvas(result, $scope.left, $scope.tops, $scope.wi, $scope.hi, $scope.per, $scope.btmR, $scope.btmL, $scope.backUrl)
.then(function () {
$timeout(function () {
//push final photo to array befor send to back end
$scope.photosToPhp.push(canvas2.toDataURL());
}, 800);
if ($scope.count < ($scope.photos[$scope.format].length - 1)) {
$scope.generate();
$scope.count++;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
console.log("test generate 3");
} else {
//all photos've been pushed now sending it to back end
$timeout(function () {
// console.log($scope.photosToPhp[0]);
$http.post('/mm3/savePhoto', $scope.photosToPhp).then(function (success) {
$scope.generating = false;
$scope.generateBtn = 'Generate';
//creating mock up gallery
for (var x = 0; x < success.data.photos; x++) {
var file = '/mm3/tmp/' + success.data.folder + "/out" + x + ".png";
$scope.gallery.push(file);
}
$scope.photosToPhp = [];
}, function (error) {
});
}, 800);
$scope.count = 0;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
}
console.log("test generate 4");
})
.catch(function (errorUrl) {
console.log(errorUrl);
})
})
};
Solved bu downgrading fabric js to 1.5 not 1.7 that i upgraded to, dont know why this worked but it dose

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Manually calling PDFJS functions. What func to call after PDFView.open to render

CanĀ“t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call! Thanks
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...

Categories

Resources