How to call variable from within a function - javascript

I can't seem to be able to call a variable set earlier by a script in order to control an element.
Script to load map onto page
<script>
window.scribblemaps = {
settings: {
baseAPI: "google",
key: 'key'
}
};
var loadmap = function () {
var sm = new
scribblemaps.ScribbleMap(document.getElementById('ScribbleMap'),
{ controlMode: { 'mapType': scribblemaps.ControlModes.SMALL } }
);
}
</script>
html which creates a div to display map
<div class="SM" id="ScribbleMap"></div>
javascript to save the map
(function($) {
$(document).ready(function() {
$('#start_design').click(function(){
var id = $(this).attr('href');
var offset = $(id).offset().top - 70;
$('body, html').animate({scrollTop: offset}, 1000);
})
$('#save_design_maps').on('click',function(){
var project_name = $('#project_name');
if( project_name.val() !== '') {
project_name.css('border-color', '');
var sm = document.getElementById('ScribbleMap');
var uid = (new Date().getTime()).toString(36);
var title = project_name.val();
var details = {
"id": uid,
"password": "aaa",
"title": title,
"description": title,
"secure": false,
"listed": false,
"projectId": "ID",
"groupCode": "<groupCode>"
};
// console.log(sm);
// console.log(JSON.stringify(sm.data.getSmJSON(), null, 2));
sm.map.save(details, function (completeEvent) { }, function (errorEvent) { });
sm.map.addListener(scribblemaps.MapEvent.MAP_SAVED, function (event) {
alert('Map is saved!');
var sm_share_link = 'https://www.scribblemaps.com/maps/view/' + title.replace(/\s+/g, '_') + '/' + uid;
$('#map_url').val(sm_share_link);
console.log(sm_share_link);
});
sm.map.addListener(scribblemaps.MapEvent.MAP_SAVE_ERROR, function (event) {
alert('Map can not be saved!');
});
} else {
alert('Please fill the Project Name Field');
project_name.css('border-color', 'red');
}
});
});
$(window).scroll(function() {
});
$(window).resize(function() {
});
$(window).load(function() {
});
})(jQuery);
Expected result is for the javascript to call a function on the Scribblemap api to Save the map.
Actual result is Uncaught TypeError: Cannot read property 'map' of undefined

Since html elements don't have the map attribute I believe that you are trying to access this sm:
var loadmap = function () {
var sm = new
scribblemaps.ScribbleMap(document.getElementById('ScribbleMap'),
{ controlMode: { 'mapType': scribblemaps.ControlModes.SMALL } }
);
}
You have to pass this sm instance to your function in order for it to work.

Related

html2canvas(document.body).then(function(canvas) {} not call

I want to call html2canvas(document.body).then(function(canvas){}); in javaScript function on button click.
Working Code:
function action () {
if (elementScope == "body") {
alert("generating pdf.........2");
//alert("canvas........."+canvas)
alert("document.body......."+document.body)
//mypdf();
html2canvas(document.body).then(function(canvas){
alert("html2canvas called...!!!");
var imageFullQuality = canvas.toDataURL();
var docDefinition = {
content: [{
image : imageFullQuality,
width : widthCanvas,
}]
};
alert("generating pdf.........4");
new pdfMake.createPdf(docDefinition).download(fileName + ".pdf");
});
}
}
Error Code
html2canvas(document.body).then(function(canvas){}); not getting call and remaining code will execute properly.
this.action = function action() {
if (elementScope == "body") {
alert("generating pdf.........2");
//alert("canvas........."+canvas)
alert("document.body......."+document.body)
//mypdf();
html2canvas(document.body).then(function(canvas){
alert("html2canvas called...!!!");
var imageFullQuality = canvas.toDataURL();
var docDefinition = {
content: [{
image : imageFullQuality,
width : widthCanvas,
}]
};
alert("generating pdf.........4");
new pdfMake.createPdf(docDefinition).download(fileName + ".pdf");
});
}
}
What is problem here didn't get. Please help me.
You can directly assign function instead of assigning function action() {}
this.action => () {
if (elementScope == "body") {
alert("generating pdf.........2");
//alert("canvas........."+canvas)
alert("document.body......."+document.body)
//mypdf();
html2canvas(document.body).then(function(canvas){
alert("html2canvas called...!!!");
var imageFullQuality = canvas.toDataURL();
var docDefinition = {
content: [{
image : imageFullQuality,
width : widthCanvas,
}]
};
alert("generating pdf.........4");
new pdfMake.createPdf(docDefinition).download(fileName + ".pdf");
});
}
}

How to have multiple list react to each other un Vue.js

Okay so I have three lists defined as Vue.js components that need to react to each other. Site, profile and Employee. This basically means that when I select a site, I want to load the profiles and the employees of this specific site, so on and so forth. The thing is that I can't figure out how to achieve this. Codewise, here's what I have:
selectw.vue
<template lang="pug">
div
.btn.dropdown-toggle.text-left.btn-block.k-selectbox-toggle(tabindex="0", v-on:keydown.down.stop="selectDown", v-on:keydown.up.stop="selectUp", v-on:keydown.enter="updateClose")
k-icon(:icon="currentOption.icon||icon||placeholderIcon", v-if="currentOption.icon||icon||(!currentOption.text&&placeholderIcon)")
span(v-if="currentOption.icon||icon||(!currentOption.text&&placeholderIcon)")
span(v-html="currentOption.html||currentOption.text||placeholder")
.dropdown-menu.pre-scrollable(v-if="searchResults.length")
.search-indicator(hidden v-if="options.length>5")
.dropdown-header.pr-3.pl-3(v-show="options.length>5")
input.form-control(type="text", :placeholder='__("Search...")', style="width:100%", v-model="searchText", v-on:keydown.down.stop="selectDown", v-on:keydown.up.stop="selectUp", v-on:keydown.enter.stop="updateClose()")
//{{__("Search...")}} FIXME because poedit is retarded
a(v-for="(option,index) in searchResults", :class="'dropdown-item '+(option.id==value?'active':'')", href="#" , v-on:mousedown="update(option.id)")
k-icon(:icon="option.icon||icon", v-if="option.icon||icon")
span(v-if="option.icon||icon")
span(v-html="option.html||option.text")
.dropdown-menu.pre-scrollable(v-else)
.dropdown-item {{__("Empty List")}}
input(type="hidden", :name="name", :value="value")
</template>
<script>
var allowClose = true;
// autofocus search in selectbox dropdowns
$(document).on('shown.bs.dropdown', function(e){
var searchInput = $(e.target).find('.search-indicator')
if(searchInput.length){
allowClose = false;
$(e.target).find('.form-control').focus();
}
});
// close on blur
$(document).on('blur', '.k-selectbox-toggle', function(e){
var element = $(this);
if(allowClose){
setTimeout(a=>{
element.next().removeClass("show") // WHY DOES THIS WORK ?!?!?!?
}, 100)
}
allowClose = true;
});
$(document).on('blur', '.k-selectbox-toggle+.dropdown-menu input.form-control', function(e){
var element = $(this);
setTimeout(a=>{
element.parent().parent().removeClass("show") // WHY DOES THIS WORK ?!?!?!?
}, 100);
});
$(document).on('focus','.k-selectbox-toggle', e => {
$(e.target).dropdown('toggle');
})
// mod negative numbers
var mod = (x, n) => ((x%n)+n)%n;
export default {
methods:{
update(id){
if(id!==undefined){
this.$emit('update:value', id)
}
},
updateClose(e){
if(this.searchResults[0]&&_.findIndex(this.searchResults, {id:this.value})==-1) this.$emit('update:value', this.searchResults[0].id);
this.$emit('update:value', this.value);
$(this.$el).find("input.form-control").blur();
$(this.$el).find(".k-selectbox-toggle").blur();
},
selectDown(e){
var index = _.findIndex(this.searchResults, {id:this.value});
if(index==-1)index=-1;
var length = this.searchResults.length;
this.value = this.searchResults[(index+1)%length].id;
e.preventDefault();
},
selectUp(e){
var index = _.findIndex(this.searchResults, {id:this.value});
if(index==-1)index=1;
var length = this.searchResults.length;
this.value = this.searchResults[mod(index-1, length)].id;
e.preventDefault();
}
},
computed:{
searchResults(){
var exclude = this.exclude||[];
if(exclude[0]&&exclude[0].id){
exclude = exclude.map(a=>a.id)
}
return this.options.filter(a=>{
return _.lowerCase(a.text)
.indexOf(
_.lowerCase(this.searchText)
) !== -1;
}).filter(a=>exclude.indexOf(a.id) == -1);
},
currentOption(){
return _.find(this.options, {id:this.value}) || _.find(this.options, {id:-1}) || (this.placeholder?{}:this.options[0]) || {}
}
},
watch:{
options(){
$(this.$el).find(".dropdown-menu").removeClass("show")
}
}
};
</script>
components.js
var modelOptions = {
sites: app.metadata.sites.map(a=>({id:a.id,text:a.name})),
profiles: app.metadata.profiles.map(a=>(
{
id: a.id,
text: a.name,
//FIXME add color tags to k-icon
html: "<span class='color-tag-group'><span data-color="+a.color+" class='color-tag'></span></span> "+a.name
}
)
),
employees: app.metadata.employees.map(a=>{
var colors = a.profiles.map(a=>"<span data-color="+a.color+" class='color-tag'></span>").join("")
return {
id: a.id,
text: a.firstname + " " + a.lastname,
html: "<span class='color-tag-group'>"+colors+"</span> "+a.firstname+" "+a.lastname
}
}),
weeks:weekList
};
var selectBoxSettings = require("./selectw.vue");
Vue.component('k-combobox', _.assign({}, selectBoxSettings, {
props:["model", "value", "placeholder", "strict", "name", "exclude", "context"],
data(){
var context = this.context || "filter";
// filter
// selection
var options = _.clone(modelOptions[this.model]);
// var options = null;
console.log('dsfsdfdsfdsfsd');
console.log(options);
var placeholderIcon = "";
if(this.model=="profiles"){
placeholderIcon = "profile"
}
if (!this.strict){
if(context=="filter"){
options.unshift({
id: -1,
text: app.utils.translate( "All " + _.capitalize(this.model) ),
icon: {profiles: "profile", employees:"user"}[this.model]
});
}
if(context=="selection"){
options.unshift({
id: null,
text: app.utils.translate( "No " + _.capitalize(this.model).slice(0, -1) ),
icon: {profiles: "profile", employees:"user"}[this.model]
});
}
}else{
if(!this.placeholder){
this.$emit('update:value', this.value||options[0].id);
}
}
var icon = "";
if(this.model=="sites"){
icon = "site"
}
return {
options,
searchText: "",
placeholderIcon,
icon
};
},
methods:{
myTesting(e){console.log("my god")}
}
}));
main.vue
<template lang="pug">
div
.btn-group.mb-3
k-combobox.btn-group(model="sites", :value.sync="currentSite")
k-combobox.btn-group(model="profiles", :value.sync="currentProfile")
k-combobox.btn-group(model="employees", :value.sync="currentEmployee")
#print-calendar.btn.btn-primary.d-print-none(onclick="window.print()")
k-icon(icon="print")
|{{__('Print')}}
.btn.mb-3
| {{__("Total:")}}
k-duration.d-inline-block(:minutes="totalMinutes")
br
div(v-if="!isDay(currentWeek)&&currentSite!=-1")
.btn-group.mb-3.mr-3
.btn.btn-primary(v-on:click="copyWeek", v-if="!isDay(currentWeek)") {{__("Copy Selected Week")}}
.btn.btn-primary(v-on:click="copyWeek", v-else) {{__("Copy Selected Day")}}
.btn-group(v-if="sourceWeek")
.btn-group.mb-3(tabindex="0", v-if="weekFuture(currentWeek)&&currentWeek!==sourceWeek")
.btn.btn-primary(v-on:click="pasteWeek") {{__("Paste")}} {{weekFormat(sourceWeek)}} {{__("Here")}}
a.btn-group.mb-3(tabindex="0", v-else, style="cursor: not-allowed", data-toggle="popover", :data-content="__('error_week_copy')")
.btn.btn-primary.disabled {{__("Paste")}} {{weekFormat(sourceWeek)}} {{__("Here")}}
//{{__("error_week_copy")}}
.modal(v-if="popupShown", style="display:block", v-on:click="hideModalSafe")
.modal-dialog.modal-lg(v-on:keydown.enter="syncSchedule()")
.modal-content
h3.modal-header {{moment(currentSchedule.start).format('YYYY-MM-DD')}}
button.close(type="button",v-on:click="popupShown=false") ×
.modal-body
.row
.col.form-group
label(for="schedule-start") {{__('Start')}}
k-input-time(:date.sync="currentSchedule.start")
.col.form-group
label(for="schedule-end") {{__('End')}}
k-input-time(:date.sync="currentSchedule.end")
.col.form-group
label(for="schedule-pause") {{__('Pause')}}
k-input-minutes(:minutes.sync="currentSchedule.pause")
.row
.col.form-group
label(for="schedule-site-id") {{__('Site')}}
k-combobox(model="sites", :value.sync="currentSchedule.site_id", strict="true", "v-on:update:value"="siteUpdateValue")
.col.form-group
label(for="schedule-profile-id") {{__('Profile')}}
k-combobox(model="profiles", :value.sync="currentSchedule.profile_id", context="selection", "v-on:update:value"="profileUpdateValue")
.col.form-group
label(for="schedule-employee-id") {{__('Employee')}}
k-combobox(model="employees", :value.sync="currentSchedule.employee_id", context="selection", "v-on:update:value"="employeeUpdateValue")
.modal-footer
.btn.btn-danger.mr-auto(v-on:click="deleteSchedule()")
k-icon(icon="delete")
| {{__('Remove')}}
.btn.btn-primary(v-on:click="syncSchedule()", tabindex="0") {{__('Save')}}
</template>
<script>
var $fullCalendar = {};
export default {
el: "#vueapp",
data: app.models.manageSchedules,
methods:{
syncSchedule(){
$fullCalendar.storeEvent(_.clone(this.currentSchedule));
this.popupShown = false;
},
deleteSchedule(){
var data={
id: this.currentSchedule.id
};
app.ajax.defaultRequest("delete", "/api/fullcalendar/"+data.id, {}, function(response){
$fullCalendar.removeEvents(data.id);
$fullCalendar.updateTotalDisplayedTime();
app.logger.debug("remove event", response);
});
this.popupShown = false;
},
hideModalSafe(e){
var $ = window.$;
if($(e.target).hasClass("modal")){
this.popupShown = false;
}
},
pasteWeek(){
var data = _.pick(this, [
"sourceWeek",
"currentSite",
"currentProfile",
"currentEmployee"
]);
data.destinationWeek = this.currentWeek;
app.ajax.calendar.copy(data, response=>{
if(response.success){
$fullCalendar.refetchEvents();
}else{
app.models.manageSchedules.layout.ajaxMessage = response.message;
}
});
},
copyWeek(){
this.sourceWeek = this.currentWeek
},
siteUpdateValue(value)
{
var self = this;
// this.loadContent();
app.ajax.defaultRequest("post", "/api/profiles", {"site_id": value}, function(response){
// console.log(response);
// console.log(app.models.manageSchedules);
self.$emit('testing', 'blbblbblb');
//app.metadata.profiles = response.data;
// app.models.manageProfileIndex.profiles = response.data;
});
},
profileUpdateValue(value)
{
},
employeeUpdateValue(value)
{
},
weekFormat(week){
var __ = app.utils.translate;
var [start, end] = week.replace(/\s/g, "").split("#").map(a=>moment(a));
var humanStart = start.format(__("MMM D"));
var humanEnd = end.format(__("MMM D"));
if(humanStart!==humanEnd){
return __("W") + start.week() //+ " - " + humanStart + " " + __("date_to") + " " + humanEnd;
}else{
return humanStart;
}
},
weekFuture(week){
var timestamp = moment(week.replace(/\s/g, "").split("#")[0]).unix()
return timestamp > moment().add(app.metadata.server_offset, 'milliseconds').unix()
},
isDay(week){
var [start, end] = week.replace(/\s/g, "").split("#");
return start === end;
}
},
watch:{
currentSite(){
$fullCalendar.refetchEvents();
this.sourceWeek = "";
},
currentProfile(){
$fullCalendar.refetchEvents();
},
currentEmployee(){
$fullCalendar.refetchEvents();
}
},
beforeCreate(){
var model = app.models.manageSchedules;
_.assign(model,{
popupShown:false,
currentSchedule:{
id: 0,
title: "",
start: "",
end: "",
pause: "",
site_id: 0,
profile_id: -1,
employee_id: -1
},
currentSite: -1,
currentProfile: -1,
currentEmployee: -1,
sourceWeek: "",
currentWeek: "",
hasCalendar: true,
totalMinutes: 0
});
var calendarConfigs = require('../fullcalendarConfigs');
calendarConfigs = _.assign({},calendarConfigs,require('./configs'));
calendarConfigs.eventDrop = function (event, delta, revertFunc){
if(moment(event.start).unix() < moment().add(app.metadata.server_offset,'milliseconds').unix()){
revertFunc();
return;
}
$fullCalendar.storeEvent(event);
}
var $calendar = $('<div class="card mb-3" id="calendar" style="cursor:copy"></div>');
$calendar.insertAfter($('#vueapp'));
$calendar.fullCalendar(calendarConfigs);
$fullCalendar = $calendar.data('fullCalendar');
$fullCalendar.addEvent = function (event) {
if(moment(event.start).unix() < moment().add(app.metadata.server_offset,'milliseconds').unix()){
return;
}
app.logger.debug('addEvent', event);
event.site_id = model.currentSite || app.metadata.sites[0].id;
event.profile_id = model.currentProfile!=-1 ? model.currentProfile || null : null;
event.employee_id = model.currentEmployee!=-1 ? model.currentEmployee || null : null;
this.storeEvent(event);
};
//---------------------------------------------------------
$fullCalendar.storeEvent = function (event) {
var fullcalendarScope = this;
app.logger.debug('fullCalendar - storeEvent', event);
var data = _.pick(event, ["id", "title", "start", "end", "pause", "site_id", "profile_id", "employee_id"])
if(data.start.local){data.start = data.start.local().format();}
if(data.end.local){data.end = data.end.local().format();}
data.type = "calendar";
app.logger.debug('storingData', data);
app.ajax.calendar.store(data, function (response) {
app.logger.debug('storeEvent', response);
var newEvent = _.pick(response, ["id", "className", "start", "end", "pause", "site_id", "profile_id", "employee_id", "title"]);
// app.models[app.metadata.route].totalMinutes = 120;
fullcalendarScope.removeEvents([event.id]);
fullcalendarScope.renderEvent(newEvent, false);
fullcalendarScope.updateTotalDisplayedTime();
});
};
//---------------------------------------------------------
$fullCalendar.editEvent = function (event) {
if(moment(event.start).unix() < moment().add(app.metadata.server_offset,'milliseconds').unix()){
return;
}
app.models.manageSchedules.currentSchedule = _.clone(event);
app.models.manageSchedules.popupShown = true;
};
$fullCalendar.updateTotalDisplayedTime = function () {
var self = this;
var displayedEvents = this.clientEvents(function(event){
if(event.start >= self.view.start && event.start <= self.view.end)
return true;
else
return false;
});
app.models[app.metadata.route].totalMinutes = _.sumBy(displayedEvents, a=>moment(a.end).diff(moment(a.start), 'minutes'));
};
var calendarSources = require('../calendarSources');
$fullCalendar.addEventSource(calendarSources.schedules);
$fullCalendar.addEventSource(calendarSources.holidays);
}
};
</script>
Okay, so as you can see, I have tree files. Selectw.vue is a component that actually defines the basic format of my listboxes. Then, you have component.js which defines the k-combobox component. This specific component is where the lists are actually populated. Right now, they're filled when the page is actually loaded. This component is also what's ultimately used on the main page (main.vue).
The lists emit an event (update:value) when their value changes and I've been able to catch it on the main page and subsequently call a script that retrieves the values I need in the database (see siteUpdateValue function). The thing is that from there, I can't access the list's content. Where I could access the list's content would be in the k-combobox definition, but at this specific place, I can't bind any form of event because there's no template.
So basically, I'm going around in circles right now and I need help figuring out the correct way to do this.
Thanks in advance.

Property undefined on production server but works on development

We've been implementing a lightbox into our wordpress theme and it works perfectly on our development server which is on the same server as our live site and the build is exactly the same to my knowledge as the build for the development site was just taken from a live site backup, but for some reason on some pages i am getting the following error but on others i'm not as if the JS isn't getting loaded before this JS file but i don't understand why it works perfectly every time on the dev server:
Uncaught TypeError: Cannot read property 'imageUrl' of undefined
jQuery(document).ready(function( $ ) {
var WHLightbox = {
settings: {
overlay: $('.portfolio-tile--overlay'),
imageCell: $('.cell-image, .portfolio-tile--image')
},
data: {
images: []
},
init: function() {
this.events();
this.buildImageData();
},
events: function() {
var self = this;
this.settings.imageCell.on('click tap', function(e) {
e.preventDefault();
e.stopPropagation();
// set up the overlay
//self._positionOverlay();
self._openOverlay();
self._preventScrolling();
// create the image slide
self._createImageSlide($(this));
});
$('.portfolio-tile--overlay--close').on('click tap', function(e) {
e.preventDefault();
e.stopPropagation();
self._closeOverlay();
});
$('.portfolio-tile--overlay--controls--prev, .portfolio-tile--overlay--controls--next').on('click tap', function(e) {
e.preventDefault();
e.stopPropagation();
});
$('.portfolio-tile--overlay--controls--prev').on('click tap', function(e) {
e.preventDefault();
e.stopPropagation();
self.showPrev();
});
$('.portfolio-tile--overlay--controls--next, .portfolio-tile--overlay').on('click tap', function(e) {
e.preventDefault();
e.stopPropagation();
self.showNext();
});
},
// public functions
showPrev: function() {
var index = this.currentImageIndex();
if(index === 0) {
index = this.data.images.length;
}
this._createImageSlide(false, index-1);
},
showNext: function() {
var index = this.currentImageIndex();
if(index === this.data.images.length-1) {
// set to -1 because it adds 1 in the _createImageSlide call
index = -1;
}
this._createImageSlide(false, index+1);
},
currentImageIndex: function() {
if(this.settings.overlay.hasClass('open')) {
var imageUrl = $('.portfolio-tile--main-image').attr('src');
for(var i=0; i<this.data.images.length; i++) {
if(this.data.images[i].imageUrl === imageUrl) {
return i;
}
}
} else {
return false;
}
},
// image data
buildImageData: function() {
var self = this,
i = 0;
this.settings.imageCell.each(function() {
self.data.images[i] = {
imageUrl: self._getImagePath($(this))
}
i++;
});
},
// slide
_createImageSlide: function($el, index) {
var imagePath;
if(!$el) {
imagePath = this.data.images[index].imageUrl;
} else {
imagePath = this._getImagePath($el);
}
this.settings.overlay.find('.portfolio-tile--main-image').attr('src', imagePath);
},
_getImagePath: function($el) {
var imagePath,
spanEl = $el.find('span.js-cell-image-background'),
imgEl = $el.find('img.cell-image__image');
if(spanEl.length) {
imagePath = spanEl.css('backgroundImage');
imagePath = imagePath.replace(/url\(["]*/,'').replace(/["]*\)/,'');
} else if(imgEl.length) {
imagePath = imgEl.attr('src');
}
return imagePath;
},
// overlay
//_positionOverlay: function() {
// this.settings.overlay.css({
// position the overlay to current scroll position
// top: $(window).scrollTop()
// });
//},
_openOverlay: function() {
this.settings.overlay.addClass('open');
},
_preventScrolling: function() {
$('html, body').addClass('no-scroll');
},
_reInitScrolling: function() {
$('html, body').removeClass('no-scroll');
},
_closeOverlay: function() {
this.settings.overlay.removeClass('open');
this._reInitScrolling();
}
};
WHLightbox.init();
});

Javascript nested dictionary null values

Below I have declared a 'class' in JS and am writing methods for it. The class represents a widget (more info class structure).
The problem I'm having is that when I print 'this' inside the setAttr ibutes method, the output is:
And when I print 'this.opts' in the very next line:
NOTE: The values of 'status' and 'power' are shown as 'null' in the second output before expanding it. This can be the only possible reason behind getting 'null' while trying to print 'this.opts.status'.
CODE
function PowerStatus(options) {
this.opts = {
meterName: '-',
displayName: null,
status: null,
power: null,
mainDiv: null,
};
this.opts = $.extend(this.opts, options);
this.opts.mainDiv = '#' + this.opts.mainDiv;
this.onClick = function () {
console.log('Clicked ' + this.opts.meterName);
};
// fill in missing attributes
this.getAttributes();
this.setHtml();
this.bindUIActions();
}
PowerStatus.prototype.getAttributes = function () {
var _this = this;
if (this.opts.displayName == null) {
getDisplayName(function (dName) {
_this.opts.displayName = dName;
}, _this.opts.meterName);
}
if (_this.opts.status == null || _this.opts.power == null) {
_this.getStatus(function (status, power) {
_this.opts.status = status;
_this.opts.power = power;
}, _this.opts.meterName)
}
};
PowerStatus.prototype.setHtml = function () {
var _this = this;
var divType = this.opts.mainDiv.split('-').slice(1).slice(0, -1).join('_');
var url = '/static/' + divType + '/html/' + divType + '.html';
$(this.opts.mainDiv).load(url, function () {
_this.setAttributes();
});
};
PowerStatus.prototype.setAttributes = function () {
var div = $(this.opts.mainDiv).find('.load-name');
var span = $('span:first', div);
span.text(this.opts.displayName);
div = $(this.opts.mainDiv).find('.load-value');
span = $('span:first', div);
span.text(this.opts.power);
};
PowerStatus.prototype.bindUIActions = function () {
var _this = this;
$(this.opts.mainDiv).on('click', function () {
_this.onClick();
});
};
PowerStatus.prototype.getStatus = function (callback) {
$.ajax({
method: "GET",
dataType: "json",
url: "/widget/power_status/status/",
data: {name: this.opts.meterName},
success: function (data) {
if (typeof callback === "function") callback(data.status, data.power);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
};
The value of this inside your click handler is not the same as the value outside that handler. You need to stash this in a local variable and use that instead.
var statusObj = this;
this.onClick = function () {
console.log('Clicked ' + statusObj.opts.meterName);
};
Alternatively, you could use .bind():
this.onClick = function () {
console.log('Clicked ' + this.opts.meterName);
}.bind(this);
The value of this is always set on every individual call to a function based on the circumstances of the call.

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