Is it possible to expose a hash property as public in the revealing module pattern?

My situation involves a standard revealing module pattern where I only want to expose a specific subset of my config settings publicly, rather than exposing all of them. However, my current approach is not functioning as expected and I am wondering if there might be a workaround or if I am overlooking something.

   var rmp = function(){
       var config = {
           someValue = "I like p&j sandwiches",
           anotherVal = {
              a: 'somevalue'
           }
       }

       var func1 = function(){
          // do some stuff

       }

       return {
           func1: func1,
           config.someValue: someValue // <-- doesn't work
           config[someValue] : someValue // <-- doesn't work
           config : config // <-- works
       }

   }

It seems that the properties of the hash are not accessible as individual entities. While creating a function that returns the value would solve the issue, I would prefer to avoid adding another function for this purpose.

      var showme = function(){
         return config.someValue;
      }


       return {
           func1: func1,
           showme: showme
       }

Answer №1

How about giving this a try:

return {
       func1: func1,
       someValue: config.someValue
}

Your config object is now kept private, except for its someValue property.

Clarification

There are a few issues to address here. Firstly, there seems to be a syntax error in your code where a comma is missing after both config.someValue: someValue and config[someValue] : someValue.

Secondly, when mentioning someValue on the right side of config.someValue: someValue, it must refer to config.someValue, not just someValue alone as it's not defined in the script.

Thirdly, I believe there may be a slight misunderstanding regarding javascript objects and the revealing module design pattern. When using the return statement, you don't need to expose properties by naming them explicitly. For instance, whateverFunc: func1 would suffice. The goal is to assign values from the actual object, like config.someValue, rather than arbitrary names.

To illustrate further, consider the following return object:

return {
    doSomething: func1,
    doAnotherThing: function () {
        return config.someValue;
    },
    getSomeValue: config.anotherVal
}

In this example, the left side represents the property name, while the right side reveals the assigned value.

Answer №2

It's not possible to selectively make properties of an object private or public. However, a workaround is to create a new object that exposes only the public properties and return that instead. For example, you can achieve this by modifying the original config object within the public object:

var customObject = function(){
  var config = {
    someValue : "I prefer tacos",
    anotherVal : {
      a: 'anothervalue'
    }
  };

  var publicConfig = Object.create(null, {
    someValue : {
      set : function(val) { config.someValue = val; },
      get : function() { return config.someValue; }
    }
  });

  var displayValue = function(){
    console.log(config.someValue);
  };

  return {
    displayValue: displayValue,
    config: publicConfig
  };
};


var obj = new customObject();
obj.displayValue(); // I prefer tacos
obj.config.someValue = 'Modified';
obj.displayValue(); // Modified

DEMO: http://jsbin.com/iJEZaBu/1/edit

Answer №3

It's important to note that you cannot simply set the subproperties of config in that manner. One way to achieve the desired result is as follows:

var rmp = function() {
   var config = {
       someValue: "I enjoy pb&j sandwiches",
       anotherVal: {
          a: 'somevalue'
       }
   }

   var func1 = function() {
      // perform actions here

   }

   return {
       func1: func1,
       config: { someValue: config.someValue },
   }

}

By using this approach, you effectively copy the specified properties from the original config within your closure to a new config stored within the returned object.

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

"Encountering issue with jQuery $.ajax DELETE not triggering then() function

I have implemented some code within a Chrome extension that effectively utilizes the then() method from the xhr response when using $.ajax. if (request && request.action === "updateTask") { $.ajax({ type: "PUT", url: config.upda ...

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...

Minimum number of coins required for a specific amount

I need assistance creating a JavaScript/jQuery function to determine the minimum number of coins required to reach a specified total amount. Here is an array object containing different coin values: var coins = [ { pennies: 200, prin ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Is there a way to prevent form submission when validation fails in an AJAX callback?

I am currently working on submitting a form with validation using ajax. After the ajax response, if the input field is valid, the form should submit; otherwise, an error message should be displayed. Below is the HTML code: <form action="new-join.php" m ...

"Adding a grid panel to the final node of a tree-grid in extjs: A step-by-step guide

Does anyone have a suggestion on how to add a grid panel to the last node/children of a treepanel dynamically? I would like to append the gridpanel dynamically and for reference, I am providing a link: Jsfiddle I also need to ensure that the gridpanel is ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

The return value of a Vuex dispatch is void

Here is the code snippet I am working with: signin(context, payload, resolve) { console.log("Processing SIGNIN action") const userEmail = payload.locmail const userPassword = payload.locpass backend.get("api/auth/signin", { headers ...

Add content to the current position of the text input field in Ionic 2 by placing

I'm currently developing a simple calculator app and I'm facing an issue. My goal is to add text at the caret position of an input text field when a button is clicked. However, the code snippet provided below is not functioning as expected: At ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

Is there a way to stop the modal from constantly fading in and out of the slider when clicked?

There is a slider with 3 modals set to appear at intervals, covering the slides with gradients. When a user clicks on a slide, the autoplay stops and allows them to select any image they want. The issue is that the modals continue to appear and disappear ...

Integrating a footer into the enhanced search tab slider

I'm struggling to create a sticky footer like the one on w3schools. Even though I used the same code in my material UI demo, it's not functioning properly. I tried debugging by changing the position from fixed to absolute, but it still isn&apos ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Building a single class in Node.js Express for use across multiple routes

In my project, I am developing APIs in the routes folder. How can I create a validation class to ensure that certain objects are not empty, null, undefined, or contain errors, and then use it across all routes? For instance, when creating a new user via a ...

ReactJs: difficulty in resetting input field to empty string

I have an application using React v 0.13.1 (Old version). I am struggling to update my input field to "" after retrieving the updated value from the database. Scenario: I am updating the input fields by clicking on the button named "Pull&qu ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Retrieve the values of a particular key from your Django queryset JSON data and then seamlessly send them over to VueJS

I recently developed a web app using Django2 with Vue for the frontend. I encountered an issue in passing all values of a specific key from JSON data to a JavaScript dictionary value on the frontend. Despite trying to use the += operator to add the data, I ...

Combining objects in an array by a specific property

In my current project, I am working with an array of objects. Each object in this array contains both an amount and a value property. What I need to achieve is that if two or more objects have the same amount value, I want to combine their values into one ...

How to implement HTML5 Application Cache in an ASP.NET MVC4 project to enable offline functionality for a web application?

Exploring the concept of app caching in HTML5 with static content and file extensions such as index.html, theme.css, and app.js. When it comes to using MVC4 for a web app, how can we cache dynamic data obtained from an API and stored in localStorage? I a ...