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.
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)&¤tSite!=-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)&¤tWeek!==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.
I can't get multiple links to work I keep getting Uncaught Reference Error:Cannot set property "imgToChange" of null(...) Could someone please tell me where I am going wrong.
"use strict";
window.onload = rolloverInit;
function rolloverInit() {
for(var i = 0;i<document.links.length;i++) {
var linkObj =document.links[i];
if(linkObj,"id") {
var linkObj =document.getElementById(linkObj.caption);
if("imgObj") {
setupRollover(linkObj,"imgObj");
}
}
}
}
function setupRollover(theLink,theImage) {
theLink.imgToChange = theImage;
theLink.onmouseout = function() {
this.imgToChange.src = this.outImage.src;
}
theLink.onmouseover = function () {
this.imgToChange.src = this.overImage.src;
}
theLink.outImage = new Image();
theLink.outImage = textImage.src;
theLink.overImage = new Image();
theLink.overImage.src = "images/" + theLink.id + "Text.gif";
}
function setupRollover(theLink,australia) {
theLink.imgToChange = "australiamap";
theLink.onmouseout = function () {
this.imgToChange.src = this.outImage.src;
}
theLink.onmouseover = function() {
this.imgToChange.src = this.overImage.src;
}
theLink.outImage = new Image();
theLink.outImage = "images/australiamap.jpg";
theLink.overImage = new Image();
theLink.overImage.src = "images/" + caption.id + "adelaide5.jpg";
}
You seem to pass null to your function, try doing a check before you call it:
function rolloverInit() {
for(var i = 0;i<document.links.length;i++) {
var linkObj =document.links[i];
if(linkObj,"id") {
var linkObj =document.getElementById(linkObj.caption);
if(linkObj !== null) { //check if linkObj is not null
setupRollover(linkObj,"imgObj");
}
}
}
}
In my application I generate a circle using the HTML element canvas.
The generation of the circle works well: the circle is correctly rendered.
The problem is that I have to put that circle in an option of a select, and as far as I know is not possible to put a canvas inside an option, therefore I probably have to convert the canvas to a base64 image so that I should be able to use it as a background-image of the option.
However, the conversion from canvas to base64 image is not working, as the browser is rendering a blank image.
I have created a fiddle for troubleshooting: https://jsfiddle.net/4hfmp0cs/
Here below you can see the javascript code of the fiddle.
function foo()
{
var circle = getStateCircle("opened");
//var gl = circle.getContext("webgl", { preserveDrawingBuffer: true });
var dataUrl = circle.toDataURL("image/png");
var img = document.createElement("img");
img.src = dataUrl;
document.getElementById("container").appendChild(img);
}
function getStateCircle(state)
{
var stateCircle;
if(state === "opened")
{
stateCircle = new Circle("#ffcc00", "20px");
}
else if(state === "accepted")
{
stateCircle = new Circle("#33cc33", "20px");
}
else if (state === "refused")
{
stateCircle = new Circle("#ff3300", "20px");
}
else if (state === "closed")
{
stateCircle = new Circle("black", "20px");
}
else
{
throw new Error("The state of the offer is unknown");
}
stateCircle.buildCircle();
var circle = stateCircle.getCircle();
return circle;
}
function Circle(color, size)
{
this._color = color;
this._size = size;
this._circle;
this.buildCircle = function()
{
var style = {
borderRadius: "50%",
backgroundColor: this._color,
height: this._size,
width: this._size
}
this._circle = new ElementBuilder("canvas").withStyleObject(style).getElement();
}
this.buildCircleAndAppendTo = function(father)
{
this._buildCircle();
father.appendChild(this._circle);
}
this.getCircle = function()
{
return this._circle;
}
}
function ElementBuilder(elementName) {
var This = this;
this.element = document.createElement(elementName);
this.withName = function (name)
{
this.element.setAttribute("name", name);
return this;
};
this.withAttribute = function (attributeName, attributeValue)
{
this.element.setAttribute(attributeName, attributeValue);
return this;
};
this.withId = function (id)
{
this.element.setAttribute("id", id);
return this;
}
this.withClass = function (className)
{
this.element.setAttribute("class", className);
return this;
}
this.addClass = function (className)
{
this.element.className = this.element.className + " " + className;
return this;
}
this.withTextContent = function (text)
{
this.element.textContent = text;
return this;
}
this.withValue = function (value)
{
this.element.value = value;
return this;
}
this.getElement = function ()
{
return this.element;
};
this.withChild = function (child)
{
this.element.appendChild(child);
return this;
};
this.withEventListener = function (type, func)
{
this.element.addEventListener(type, func);
return this;
};
this.withClickEventListener = function (func)
{
this.element.addEventListener("click", func);
return this;
}
this.withDoubleClickEventListener = function (func)
{
this.element.addEventListener("dblclick", func);
return this;
}
this.withStyle = function (styleAttribute, value)
{
this.element.style[styleAttribute] = value;
return this;
}
this.withStyleObject = function (styleObject)
{
ensureIsAnObject(styleObject);
var keys = Object.keys(styleObject);
keys.forEach(function (elt) {
This.withStyle(elt, styleObject[elt]);
});
return this;
}
}
function ensureIsAnObject(value, argumentName) {
if (!(typeof value == "object")) {
throw new Error("The argument '" + argumentName + "' should be an object, but it's type is --->" + typeof value);
}
}
The HTML code
<div id="container">
</div>
<button onclick="foo()">Append image</button>
Nowhere are you actually drawing to the canvas, just styling it with css, which is rendered separate from the canvas. You can replace the canvas with a div, or any other block element and just append that to the document to get the correct effect.
Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
Or Check in
http://jsfiddle.net/simonsarris/vgmFN/
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)
})
}
}
})();