From the example, I think it will be clear what I mean:

var preloadImages = function (imageIn) { var imageIn = (typeof imageIn !== "object") ? [imageIn] : imageIn; this.arrayImages = []; this.loadedimages = 0; var progressLoad = function () { } var completeLoad = function () {} var imageLoadCheck = function () { progressLoad(++this.loadedimages); if (this.loadedimages === imageIn.length) { completeLoad(this.arrayImages); } } for (var i = 0; i < imageIn.length; i++) { this.arrayImages[i] = new Image(); this.arrayImages[i].src = imageIn[i]; this.arrayImages[i].onload = function () { imageLoadCheck(); } this.arrayImages[i].onerror = function () { imageLoadCheck(); } } return { complete: function (f) { completeLoad = f || completeLoad; }, progress: function (f) { progressLoad = f || progressLoad; } } } var imageList = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg']; preloadImages(imageList).progress(function (namber) { console.log(namber); }).complete(function (images) { console.log('Loading all image: ' + images.length); }) 

We get: Uncaught TypeError: Cannot call method 'complete' of undefined Tell me how to properly implement this? or stick a finger where it is written, because not found (

    1 answer 1

    Chaining pattern , I think, will help you. Rewrite the preloadImages() function according to this pattern, somewhat modifying it. Here is the simplest example:

     var preloadImages = function () { this.complete = function(f) { f(); return this; } this.progress = function(f) { f(); return this; } return this; } preloadImages().progress(function(){ console.log('In progress') }).complete(function(){ console.log('Completed') }) 

    In the console appears:

     In progress Completed Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…} 

    It's simple!