JavaScript newbie diving into the revealing module pattern

Currently diving into Addy Osmani's fantastic read on javascript design patterns, however, I'm facing a roadblock. Can someone help me identify the issue with my approach? (I'm experimenting with Raphael for fun):

var myPaper = Raphael('container', '800', '600');

var myScene = function() {
  var c1 = myPaper.circle(50, 50, 40);
  var c2 = myPaper.circle(50, 150, 40);
  var c3 = myPaper.circle(50, 250, 40);

  c2.attr("fill", "red");  // Yes!

  return {
      firstCircle: c1
  };
}

// Later on, I want to execute the function...
myScene();

//  ...and even later, I wish to reference one of the circles
//  without having to create another global variable.

myScene.firstCircle.attr("fill", "red");  // Incorrect!
console.log(myScene.firstCircle); //  undefined!

http://jsfiddle.net/aGCv8/

Answer ā„–1

"There's a flaw in the method you're using," is that this does not follow the module pattern, whether revealing or not. If you intended to utilize it, do so, and ensure the function self-invokes:

var myScene = function() {
  var c1 = myPaper.circle(50, 50, 40);
  var c2 = myPaper.circle(50, 150, 40);
  var c3 = myPaper.circle(50, 250, 40);

  c2.attr("fill", "red");  // yes!

  return {
      firstCircle: c1         // ā† reference an actual variable
  };
}();                          // ā† place parentheses here

You do not later call myScene like a function, as it is not a function, and that unnamed function has already been invoked. And behold, you still have access to that circle!

console.log(myScene.firstCircle); // z {0: circle.[object SVGAnimatedString], node: circle.[object SVGAnimatedString], id: 0, matrix: cb, realPath: null, paper: jā€¦}

If you omit the parentheses (which triggers the unnamed function), you will see a notably different result, as you've discovered.

http://jsfiddle.net/mattball/qR4Fj/

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

Ensure that the content-length header is properly set for each section of a multipart/form-data upload

I am looking to send a post request with multiple files using the multipart/form-data type. It's important for me to know the file size (content-length) of each file on the server side. When constructing the POST request in Javascript, I utilize a Fo ...

Utilizing directive scope variables to generate dynamic templates

Looking for a solution to dynamically render forms with various controls based on a specific Type value specified in a JSON object. The form will be created based on user input, so the necessary question types may vary. While we will define the types, they ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

Keep track of open tabs and their content by utilizing sessions

I am working with Bootstrap Tabs where I have loaded content dynamically using jQuery's load() function. In addition, when a button is clicked, a new tab is generated automatically with a basic HTML form containing various input fields, which is then ...

React Native, state values are stagnant

I created an edit screen where I am attempting to update the post value through navigation v4 using getParams and setParams. However, when I modify the old value and click the save button, it does not update and no error is displayed. The old values still ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Display the JSON outcome with console.logging

As I delve into the world of APIs, JSON, and JQuery, I've encountered a roadblock. How can I retrieve the following information, "name: The Old Mill Cafe," and log it to the console from my JQuery call? Below is my current code snippet: $(document). ...

My HTML file is not able to load my Javascript file

I'm currently working on integrating a JavaScript code for a show more and show less feature on my page. The goal is to limit the description so that it shows only a certain number of characters, with an option to expand or collapse the text. However, ...

When the div tag exceeds its boundaries, apply a new class

I am working on a div with set dimensions, and I am populating it with content using ng-repeat. My goal is to apply a CSS class to this div when it exceeds its limits. I attempted to use the length property but without success. var app = angular.module( ...

Develop an asynchronous function that can fetch a result at a later time within an Express route

I need to retrieve an Excel file from Box.com using their API and then convert the Excel data into JSON format. Afterwards, I plan to display this JSON data using Express and Handlebars. Below is the function I've created for fetching the Excel file ...

Is there a way to reposition a popup window to the center of the page after launching it?

popup = window.open(thelink,'Facebook Share','resizable=1,status=0,location=0, width=500,height=300'); My goal is to perfectly center this popup window both vertically and horizontally. ...

Guide on Embedding a JavaScript Encapsulation Function within a Directive

I have encountered a situation where implementing an encapsulating function breaks my directive. Strangely, without the encapsulation, everything works fine. Has anyone else faced this issue before or can shed some light on why it might be causing the dire ...

An easy guide to dynamically assigning a property using jQuery

I am currently utilizing the toastr plugin and I would like to dynamically set the options using a JSON object that is retrieved from an AJAX call. I am encountering some difficulties in setting the options property and value programmatically. Below is a s ...

Tips for resolving Vue.js static asset URLs in a production environment

I included the line background-image: url(/img/bg.svg); in my CSS file. During development mode, this resolves to src/img/bg.svg since the stylesheet is located at src/css/components/styles.css. However, when I switch to production mode, I encounter a 40 ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Remove any JSON objects in JavaScript or AngularJS that match another JSON object

JSON A ['711','722','733','744'] JSON B [{pid: 711, name: 'hello'},{pid: 733, name: 'world'}, {pid: 713, name: 'hello'},{pid: 744, name: 'hellosdaf'}] I am attempting to remo ...

Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during ...

Is it possible to create a component with a button that triggers the rendering of a different component?

I am struggling to implement an 'edit' button within a component that, upon clicking, should display a separate component known as a 'client edit modal'. I'm facing challenges in figuring out how to achieve this functionality. The ...

Incorporating a node module into my Angularjs application

Recently, I stumbled upon a handful of modules that I would like to incorporate into my Angular app. However, I find myself at a crossroads on how to effectively integrate them into my project as I will need to use "require()" in my factory file. One part ...