Decoding the Blueprint of Easel in JavaScript

Recently, I came across a fantastic API that promises to simplify working with CANVAS by allowing easy selection and modification of individual elements within the canvas. This API is known as EaselJS, and you can find the documentation here.

While I found the API itself to be quite straightforward, I stumbled upon some JavaScript code that left me puzzled. Specifically, the part enclosed in * * that I couldn't quite decipher. I was curious about the type of JavaScript structure being used here.

(function(target){...content...})(bitmap) and in the content, it references bitmap, which is something outside.

Here is a snippet of the code:

   for(var i = 0; i < 100; i++){
    bitmap = new Bitmap(image);
    container.addChild(bitmap);
    bitmap.x = canvas.width * Math.random()|0;
    bitmap.y = canvas.height * Math.random()|0;
    bitmap.rotation = 360 * Math.random()|0;
    bitmap.regX = bitmap.image.width/2|0;
    bitmap.regY = bitmap.image.height/2|0;
    bitmap.scaleX = bitmap.scaleY = bitmap.scale = Math.random()*0.4+0.6;
    bitmap.mouseEnabled = true;
    bitmap.name = "bmp_"+i;

(function(target) {

*bitmap.onPress = function(evt) *

        {if (window.console && console.log) { console.log("press!"); }
        target.scaleX = target.scaleY = target.scale*1.2;
        container.addChild(target);
        // update the stage while we drag this target
        //Ticker provides a central heartbeat for stage to listen to
        //At each beat, stage.tick is called and the display list re-rendered
        Ticker.addListener(stage);
        var offset = {x:target.x-evt.stageX, y:target.y-evt.stageY};

        evt.onMouseMove = function(ev) {
            target.x = ev.stageX+offset.x;
            target.y = ev.stageY+offset.y;
            if (window.console && console.log) { console.log("move!"); }
        }
        evt.onMouseUp = function() {
            target.scaleX = target.scaleY = target.scale;
            // update the stage one last time to render the scale change, then stop updating:
            stage.update();
            Ticker.removeListener(stage);
            if (window.console && console.log) { console.log("up!"); }
        }

** }})(bitmap); **

    bitmap.onClick = function() { if (window.console && console.log) { console.log("click!"); } }
}

Answer №1

(function(container){...uniqueContent...})(image) 

establishes a contained scope for uniqueContent to prevent any declarations from leaking into the broader scope. Within uniqueContent, container acts as an alias for image.

This concept may be likened to

function start(container) { ...uniqueContent... }

followed by an immediate invocation using image as the specific value for the container parameter, however, the former approach has an even lesser impact on the global scope -- it does not introduce start as a global name.

UPDATE: The objective is not necessarily about lexical scoping, but rather to ensure that event handlers correctly reference the intended image, instead of the last one processed by the loop. start(image);

Refer to Event handlers inside a Javascript loop - need a closure? for further insights.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to fix jQuery animate queue issue so animations run at the same time

Previously, I successfully used the jQuery queue modifier for simultaneous animations. However, this time around, I am facing difficulties in getting it to work. You can view the issue on the following page: . When you click on "notifications" at the top ...

Utilizing Angular 1.5 and ES6 to Enhance Dependency Injection

Hi there, I am currently exploring Angular and attempting to integrate ES6 into my workflow. I seem to be facing an issue with dependency injection where I cannot seem to get it working as expected. Here is a snippet from my index.js file: import ...

What is the solution for fixing the '$ not defined error' in a .js file with $ajax code?

var example = document.createElement("SCRIPT"); example.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"; var nodeScript= document.createTextNode("function test() {console.log('test message');$.ajax({ type: \"POST&bs ...

Using AngularJS in conjunction with other scripts

I am currently working on an application and now I have the task of implementing a dynamic menu using AngularJS. This requires me to modify variables in the AngularJS application from my existing code. Here is the example I am experimenting with: <scr ...

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

How can JavaScript effectively retrieve the JPEG comment from a JPEG file?

How can one properly retrieve the JPEG comment field (not EXIF, but the COM field) from a JPEG file using JavaScript, particularly when running node on the command line? While there are several libraries available for reading EXIF data in JavaScript, I ha ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

Altering iframe Content with the Help of Selenium Web Driver

I am looking to update the content of an iframe with new material using Selenium WebDriver. Note: I have attempted the following method: driver.swithTo().frame(frame_webelement); driver.findElement(By.xxx).sendKeys("Mycontent"); While I was able to cle ...

Managing embedded URLs in Next.js applications

I am currently in the process of developing an ecommerce platform, expecting users to utilize both our domain and their own custom domains. For example: ourplatform.com/username theirdomain.com My goal is to customize the inline links based on the speci ...

How to Retrieve Content from an iFrame Using jQuery?

I am facing a challenge with an HTML form that is directed to an IFRAME upon clicking "submit". The iframe then loads a page after the submission, which indicates whether the user-input data is valid or not. It simply displays on screen as "TRUE" or "FALSE ...

What is the best way to arrange buttons in a row horizontally?

Desired Output I need help aligning the buttons as shown in the Desired Output image, but when I run the code, the buttons stack vertically, resulting in Output like this. I've included the HTML, CSS, and JS code below. As a beginner in UI design, I ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

Concerns regarding the set-up of the latest React application

My goal is to become proficient in React, so I decided to install Node.js (v 10.16.0 LTS) and run the following commands using Windows Powershell: npx create-react-app my-app cd my-app npm start However, after making changes to the code (such as modifyin ...

Encountering Karma Angular Error: Name 'X' Not Found

After executing Karma Start in my Angular project, I am encountering several errors. All the error messages highlight issues like 'Cannot find name Blob', 'Cannot Find name KeyboardEvent', 'Cannot find name HTMLElement', amon ...

Is there a way to change the color of the menu button to white if the points are not visible?

I have created CSS to style the menu's color and make the buttons change color based on different actions. However, I also want the buttons to match the colors of the points on the map. To achieve this, I set the background color in JavaScript when ge ...