Init Object with different parameters - javascript

I have an object and I call it many times in my page, but with different parameters.
var lazyLoad = (function () {
var CONFIG = {
block: '',
url: ''
}
function work(){
window.d = document
var buffer = ''
d.write = d.writeln = function(s){ buffer += s }
d.open = d.close = function(){}
s = d.createElement('script')
s.setAttribute('type','text/javascript')
s.setAttribute('src',CONFIG.url)
d.getElementById(CONFIG.block).appendChild(s)
s.onload = function () {
window.setTimeout(function() {
console.warn(CONFIG.block + ' ' + buffer)
d.getElementById(CONFIG.block).innerHTML += buffer
buffer = ''
}, 0)
}
}
return {
init: function (options) {
$.extend(CONFIG, options);
random = $('#'+CONFIG.block).attr('rel')
id = $('#'+CONFIG.block).attr('id').replace(random,'')
id = id.replace('DIV','')
size = id.split('X')
ele_width = size[0] || CONFIG.width
ele_height = size[1] || CONFIG.height
$('#'+CONFIG.block).css({
'width':ele_width+'px',
'height':ele_height+'px',
'background':'url(/static/i/ajax-loading-black.gif) no-repeat center center'
})
console.log(CONFIG.block)
$(window).load(function(){
work()
})
}
}
})();
I call it like this:
lazyLoad.init({
url: 'http://example.com/test1.js',
block: DIVID1
})
Than
lazyLoad.init({
url: 'http://test.com/test2.js',
block: DIVID2
})
And than:
lazyLoad.init({
url: 'http://testdomain.com/test3.js',
block: DIVID3
})
After loading the document I see that each div has width and height, which is applied with this script, but buffer was inserted only in last div.

The problem is that CONFIG is declared in the outer function, since javascript is all single threaded(ignore WebWorkers here =)) at the timeyour work function is called the values in CONFIG are the right ones. But since every time you do $.extend(CONFIG, options); you change the same object by the time s.onload is fired the value left in CONFIG.block is the last one used. Try:
var lazyLoad = (function () {
//var CONFIG = {
// block: '',
// url: ''
//}
function work(options){
window.d = document
var buffer = ''
d.write = d.writeln = function(s){ buffer += s }
d.open = d.close = function(){}
s = d.createElement('script')
s.setAttribute('type','text/javascript')
//s.setAttribute('src',CONFIG.url)
//d.getElementById(CONFIG.block).appendChild(s)
s.setAttribute('src',options.url)
d.getElementById(options.block).appendChild(s)
s.onload = function () {
window.setTimeout(function() {
//console.warn(CONFIG.block + ' ' + buffer)
//d.getElementById(CONFIG.block).innerHTML += buffer
console.warn(options.block + ' ' + buffer)
d.getElementById(options.block).innerHTML += buffer
buffer = ''
}, 0)
}
}
return {
init: function (options) {
var CONFIG = {
block: '',
url: ''
}
$.extend(CONFIG, options);
random = $('#'+CONFIG.block).attr('rel')
id = $('#'+CONFIG.block).attr('id').replace(random,'')
id = id.replace('DIV','')
size = id.split('X')
ele_width = size[0] || CONFIG.width
ele_height = size[1] || CONFIG.height
$('#'+CONFIG.block).css({
'width':ele_width+'px',
'height':ele_height+'px',
'background':'url(/static/i/ajax-loading-black.gif) no-repeat center center'
})
console.log(CONFIG.block)
$(window).load(function(){
//work()
work(CONFIG)
})
}
}
})();

Related

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

canvas is distorting itself and moving (fabric.js)

I just need an advice on where to look at or where to start as right now I am confused. Not sure if this is CSS issue, javascript, or fabric.js
Problem:
- I am adding a background image to canvas and sometimes it behaves really strange. And canvas is distorting itself sometimes on click, sometimes on resize, sometimes just without doing nothing. But this does not happen always.
These are two videos with the issue:
https://jumpshare.com/v/4FU3xWjqk4h6j0OwqaFs (this is just without
doing nothing).
https://jumpshare.com/v/tBS7NJC5VgccWnIssETw (this is me clicking on canvas)
This is how I add an image to canvas (fetching url via API):
$scope.openBlob = function($event, imageURL) {
$rootScope.isLoading();
$rootScope.centerSpinner();
if ($rootScope.currentTab === 1) {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-images" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
} else {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-new-middle" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
}
$rootScope.isAlsoLoading = true;
$http({
method: "GET",
url: imageURL.full,
responseType: "blob"
}).then(
function(res) {
var reader = new FileReader();
reader.readAsDataURL(res.data);
reader.onload = function(e) {
canvas.loadMainImage(e.target.result);
$rootScope.started = true;
$rootScope.uploaded = true;
$rootScope.changeStyling();
};
},
function(res) {
console.log("For some reasons it failed to open", res);
});
if ($rootScope.currentTab === 1) {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-images").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
} else {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-new-middle").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
}
}
LoadMainImage function content:
loadMainImage: function(url, height, width, dontFit, callback) {
var object;
fabric.util.loadImage(url, function(img) {
//img.crossOrigin = 'anonymous';
object = new fabric.Image(img, canvas.imageStatic);
object.name = 'mainImage';
if (width && height) {
object.width = width;
object.height = height;
}
canvas.mainImage = object;
canvas.fabric.forEachObject(function(obj) {
console.log('image object', obj);
if (obj && obj.name == 'mainImage') {
canvas.fabric.remove(obj);
}
});
canvas.fabric.add(object);
object.top = -0.5;
object.left = -0.5;
object.moveTo(0);
canvas.fabric.setHeight(object.height);
canvas.fabric.setWidth(object.width);
canvas.original.height = object.height;
canvas.original.width = object.width;
$rootScope.canvaswidth = canvas.original.width;
$rootScope.canvasheight = canvas.original.height;
$rootScope.calculateImageType(canvas.original.width, canvas.original.height);
if ($rootScope.gridadded) {
$rootScope.removeGrid();
$rootScope.addGrid();
}
if (!dontFit) {
canvas.fitToScreen();
}
$rootScope.$apply(function() {
$rootScope.$emit('editor.mainImage.loaded');
});
if (callback) {
callback();
}
});
},
Fit to screen function:
$scope.fitToScreen = function () {
$scope.zoom = canvas.currentZoom * 100;
if (canvas.mainImage) {
var oWidth = canvas.mainImage.width,
oHeight = canvas.mainImage.height;
} else {
var oWidth = canvas.original.width,
oHeight = canvas.original.height;
}
var maxScale = Math.min(3582 / oHeight, 5731 / oWidth) * 100,
minScale = Math.min(141 / oHeight, 211 / oWidth) * 100;
$scope.maxScale = Math.ceil(maxScale);
$scope.minScale = Math.ceil(minScale);
canvas.zoom(canvas.currentZoom);
};
UPDATE: I am assuming that it might be scaling (zooming in and zooming out issue)

JQuery: collection array length being capped at 100

I'm using Splunk Web Framework and Google Maps app to create a custom map implementation. The problem i'm seeing is when I send splunk search results information into the google maps js it caps my rows at 100. Can someone take a look at the code below and see if there any anywhere that might cause an array to be capped at 100?
/** #license
* RequireJS plugin for async dependency load like JSONP and Google Maps
* Author: Miller Medeiros
* Version: 0.1.1 (2011/11/17)
* Released under the MIT license
*/
define('async',[],function(){
var DEFAULT_PARAM_NAME = 'callback',
_uid = 0;
function injectScript(src){
var s, t;
s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src;
t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s,t);
}
function formatUrl(name, id){
var paramRegex = /!(.+)/,
url = name.replace(paramRegex, ''),
param = (paramRegex.test(name))? name.replace(/.+!/, '') : DEFAULT_PARAM_NAME;
url += (url.indexOf('?') < 0)? '?' : '&';
return url + param +'='+ id;
}
function uid() {
_uid += 1;
return '__async_req_'+ _uid +'__';
}
return{
load : function(name, req, onLoad, config){
if(config.isBuild){
onLoad(null); //avoid errors on the optimizer
}else{
var id = uid();
window[id] = onLoad; //create a global variable that stores onLoad so callback function can define new module after async load
injectScript(formatUrl(name, id));
}
}
};
});
requirejs.s.contexts._.nextTick = function(f){f()}; require(['css'], function(css) { css.addBuffer('splunkjs/css/googlemap.css'); }); requirejs.s.contexts._.nextTick = requirejs.nextTick;
define('splunkjs/mvc/googlemapview',['require','exports','module','underscore','./mvc','./basesplunkview','./messages','async!http://maps.googleapis.com/maps/api/js?sensor=false','css!../css/googlemap.css'],function(require, exports, module) {
var _ = require('underscore');
var mvc = require('./mvc');
var BaseSplunkView = require("./basesplunkview");
var Messages = require("./messages");
require("async!http://maps.googleapis.com/maps/api/js?sensor=false");
require("css!../css/googlemap.css");
var GoogleMapView = BaseSplunkView.extend({
moduleId: module.id,
className: "splunk-googlemap",
options: {
managerid: null,
data: "preview"
},
initialize: function() {
this.configure();
this.bindToComponentSetting('managerid', this._onManagerChange, this);
this.map = null;
this.markers = [];
// If we don't have a manager by this point, then we're going to
// kick the manager change machinery so that it does whatever is
// necessary when no manager is present.
if (!this.manager) {
this._onManagerChange(mvc.Components, null);
}
},
_onManagerChange: function(managers, manager) {
if (this.manager) {
this.manager.off(null, null, this);
this.manager = nul=]=]l;
}
=]== if (this.resultsModel) {
= this.resultsModel.off(null, null, this);
this.resultsModel.destroy();
this.resultsModel = null;
}
if (!manager) {
this.message('no-search');
return;
}
// Clear any messages, since we have a new manager.
this.message("empty");
this.manager = manager;
this.resultsModel = manager.data(this.settings.get("data"), {
output_mode: "json_rows"
});
manager.on("search:start", this._onSearchStart, this);
manager.on("search:progress", this._onSearchProgress, this);
manager.on("search:cancelled", this._onSearchCancelled, this);
manager.on("search:error", this._onSearchError, this);
this.resultsModel.on("data", this.render, this);
this.resultsModel.on("error", this._onSearchError, this);
manager.replayLastSearchEvent(this);
},
_onSearchCancelled: function() {
this._isJobDone = false;
this.message('cancelled');
},
_onSearchError: function(message, err) {
this._isJobDone = false;
var msg = message;
if (err && err.data && err.data.messages && err.data.messages.length) {
msg = _(err.data.messages).pluck('text').join('; ');
}
this.message({
level: "error",
icon: "warning-sign",
message: msg
});
},
_onSearchProgress: function(properties) {
properties = properties || {};
var content = properties.content || {};
var previewCount = content.resultPreviewCount || 0;
var isJobDone = this._isJobDone = content.isDone || false;
if (previewCount === 0 && isJobDone) {
this.message('no-results');
return;
}
if (previewCount === 0) {
this.message('waiting');
return;
}
},
_onSearchStart: function() {
this._isJobDone = false;
this.message('waiting');
},
clearMarkers: function() {
var count = this.markers.length;
for (var i = 0; i < count; ++i)
this.markers[i].setMap(null);
this.markers.length = 0;
},
createMap: function() {
this.map = new google.maps.Map(this.el, {
center: new google.maps.LatLng(47.60, -122.32),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.map.setOptions(this.options);
},
message: function(info) {
this.map = null;
Messages.render(info, this.$el);
},
render: function() {
if (!this.manager) {
return;
}
if (!this.resultsModel || !this.resultsModel.hasData()) {
if (this.resultsModel && !this.resultsModel.hasData() && this._isJobDone) {
this.message("no-results");
}
return this;
}
if (!this.map) {
this.createMap();
}
var that = this;
this.clearMarkers();
this.resultsModel.collection().each(function(row) {
var lat = parseFloat(row.get("lat"));
var lng = parseFloat(row.get("lng"));
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: that.map
});
that.markers.push(marker);
});
return this;
}
});
return GoogleMapView;
});
requirejs.s.contexts._.nextTick = function(f){f()}; require(['css'], function(css) { css.setBuffer('/* */\n\n/* Bootstrap Css Map Fix*/\n.splunk-googlemap img { \n max-width: none;\n}\n/* Bootstrap Css Map Fix*/\n.splunk-googlemap label { \n width: auto; \n display:inline; \n} \n/* Set a small height on the map so that it shows up*/\n.splunk-googlemap {\n min-height: 100px;\n height: 100%;\n}\n'); }); requirejs.s.contexts._.nextTick = requirejs.nextTick;
From a quick search it seems it could be splunk capping at 100?
See http://answers.splunk.com/answers/52782/100-result-limit-in-js-sdk.html

How to execute this function without clicking on a button

So this is a part of greasemonkey userscript. It's an adviser for an online game. At the end of it i've got this:
function do_login() {
// var loc = reg2.exec(document.location.href);
//Auto backing to login page
if (document.location.href.search("logout") != -1) {
window.setTimeout(function () {
document.location.href = "http://www" + gamepage;
}, 100);
}
else {
//login
try {
var logindata = explode(GM_getValue("logindata", "[]"));
}
catch (err) {
var logindata = new Array;
}
unsafeWindow.showDiv("login_div");
$("login_div").style.zIndex = "20";
$("login_div").getElementsByClassName("kh_btn")[0].addEventListener("click", function () {
var currServer = $("l_server").value;
var currUser = $("l_loginname").value.toLowerCase();
GM_setValue(lng + "_" + currServer + "_username", currUser);
}, false);
function submit_login(currUserNr) {
$("l_server").value = logindata[currUserNr][1];
$("l_loginname").value = logindata[currUserNr][2];
$("l_password").value = logindata[currUserNr][3];
$("login_div").getElementsByClassName("kh_btn")[0].click();
}
var newdiv = createElement("div", {style: "position:absolute;top:0px;left:0px;width:412px;padding:10px;background-color:#999;-moz-border-radius:10px;"}, $("login_div"));
for (var v = 0; v < logindata.length; v++) if (logindata[v][1] != "0") {
var newbutton = createElement("button", {type: "button", class: "cursorclickable", id: "autologin" + v, style: "width:200px;height:20px;margin:3px;"}, newdiv, texte["server"] + " " + logindata[v][1] + "." + logindata[v][0] + ": " + logindata[v][2]);
newbutton.addEventListener("click", function () {
submit_login(this.id.replace("autologin", ""));
}, false);
}
newdiv = null;
newbutton = null;
}
}
It's executed when script finds "logout" in the url.
Now, everything works, it's entering main-page, creating a button, the button itself works, but now i would like to execute "onlick" automatically.
You could select the element and then invoke the .click() method:
document.querySelector('#myElement')[0].click();

Accessing a jQuery Closure function outside

I have this code embedded in my file for managing session time out. This was referred from http://www.fairwaytech.com/2012/01/handling-session-timeout-gracefully/
I want to call SessionManager.extend() for all the ajax request
complete. So i can automatically refresh my session manager time.
This is what i tried
<script type="text/javascript">
$(document).ajaxSuccess(function (event, xhr, settings) {
if (xhr.status === 200) {
SessionManager().extend();
}
});
</script>
Getting an error that SessionManager object not found. How do we call this?
Below is the library code taken from that site
$(function () { // Wrap it all in jQuery documentReady because we use jQuery UI Dialog
// HtmlHelpers Module
// Call by using HtmlHelpers.getQueryStringValue("myname");
var HtmlHelpers = function () {
return {
// Based on http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
getQueryStringValue: function (name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
};
} ();
// StringHelpers Module
// Call by using StringHelpers.padLeft("1", "000");
var StringHelpers = function () {
return {
// Pad string using padMask. string '1' with padMask '000' will produce '001'.
padLeft: function (string, padMask) {
string = '' + string;
return (padMask.substr(0, (padMask.length - string.length)) + string);
}
};
} ();
// SessionManager Module
var SessionManager = function () {
// NOTE: globalTimeoutPeriod is defined in _Layout.cshtml
var sessionTimeoutSeconds = HtmlHelpers.getQueryStringValue('smt') || (globalTimeoutPeriod),
countdownSeconds = HtmlHelpers.getQueryStringValue('smc') || 300,
secondsBeforePrompt = sessionTimeoutSeconds - countdownSeconds,
$dlg,
displayCountdownIntervalId,
promptToExtendSessionTimeoutId,
originalTitle = document.title,
count = countdownSeconds,
extendSessionUrl = '/Session/Extend',
expireSessionUrl = '/Session/Expire?returnUrl=' + location.pathname;
var endSession = function () {
$dlg.dialog('close');
location.href = expireSessionUrl;
};
var displayCountdown = function () {
var countdown = function () {
var cd = new Date(count * 1000),
minutes = cd.getUTCMinutes(),
seconds = cd.getUTCSeconds(),
minutesDisplay = minutes === 1 ? '1 minute ' : minutes === 0 ? '' : minutes + ' minutes ',
secondsDisplay = seconds === 1 ? '1 second' : seconds + ' seconds',
cdDisplay = minutesDisplay + secondsDisplay;
document.title = 'Expire in ' +
StringHelpers.padLeft(minutes, '00') + ':' +
StringHelpers.padLeft(seconds, '00');
$('#sm-countdown').html(cdDisplay);
if (count === 0) {
document.title = 'Session Expired';
endSession();
}
count--;
};
countdown();
displayCountdownIntervalId = window.setInterval(countdown, 1000);
};
var promptToExtendSession = function () {
$dlg = $('#sm-countdown-dialog')
.dialog({
title: 'Session Timeout Warning',
height: 250,
width: 350,
bgiframe: true,
modal: true,
buttons: {
'Continue': function () {
$(this).dialog('close');
refreshSession();
document.title = originalTitle;
},
'Log Out': function () {
endSession(false);
}
}
});
count = countdownSeconds;
displayCountdown();
};
var refreshSession = function () {
window.clearInterval(displayCountdownIntervalId);
var img = new Image(1, 1);
img.src = extendSessionUrl;
window.clearTimeout(promptToExtendSessionTimeoutId);
startSessionManager();
};
var startSessionManager = function () {
promptToExtendSessionTimeoutId =
window.setTimeout(promptToExtendSession, secondsBeforePrompt * 1000);
};
// Public Functions
return {
start: function () {
startSessionManager();
},
extend: function () {
refreshSession();
}
};
} ();
SessionManager.start();
});
Remove the var prefix from SessionManager.
Bit of info here about scope, http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx

Categories

Resources