Utilizing module pattern in JavaScript to reveal computed knockout settings

I've encountered an issue while using knockout with the revealing module pattern. My goal is to pass an observable by reference and have its value based on a computed function. However, it seems like the observable is being passed in by value instead of reference.

The listPersonClientSelect variable is an observable(), and I want to pass it into a JavaScript function to establish a computed calculation based on changes in select2Data(). You can see in the code below that I am passing the observable as a parameter in the init function, but I want to set its value to the computed result.

The init function is called as follows:

self.assigneePersonSetupKO.listPersonClientSetup shows the computed result, but what I really need is for self.assignees() to reflect these changes (the value of the computed result).

Is there a way to pass self.assignees into the revealing module pattern in JavaScript by reference?

self.assigneePersonSetupKO = new PersonSetupKO();
self.assigneePersonSetupKO.init(self.assignees);

var PersonSetupKO = function () {
    "use strict";
    
    //var self = this;
    var select2Data = ko.observable(''),
        initialOptions = [],
        initialSelectedOptions = [],        
        listPersonClientSelect = ko.observable(),
                
        init = function (listPersonClientSelect) {
            this.initialOptions = $.map(listPersonClientSelect(), function (item) {
                return { DisplayName: item.DisplayName(), Gen: item.Id() }
            });

            this.initialSelectedOptions = $.map(listPersonClientSelect(), function (item) {
                return item.Gen();
            });

            this.select2Data($.map(listPersonClientSelect(), function (item) {
                return { text: item.DisplayName(), id: item.Id() };
            });

            
            this.listPersonClientSelect = ko.computed(function () {
                var results = $.map(select2Data(), function (item) {
                    return {
                        DisplayName: ko.observable(item.text),
                        Id: ko.observable(item.id)
                    }
                });
                return results;
            });
        };

    return {       
        init: init,
        select2Data: select2Data,
        initialOptions: initialOptions,
        initialSelectedOptions: initialSelectedOptions,
        listPersonClientSelect: listPersonClientSelect
        
    };

};

Answer №1

When dealing with observables, it's important to remember that they are always passed by reference. This means that the init function receives a reference to the original observable. To make changes to the observable, you simply need to write to it:

this.updateListPersonClientSelect = ko.computed(function () {
    var results = $.map(select2Data(), function (item) {
        return {
            DisplayName: ko.observable(item.text),
            Id: ko.observable(item.id)
        }
    });
    listPersonClientSelect(results);
});

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

Creating a unique custom bottom position for the popover and ensuring it is fixed while allowing it to expand

Creating a customized popover similar to Bootstrap's popover, I have successfully implemented popovers in all directions except for the top direction. My challenge lies in fixing the popover at the bottom just above the button that triggers it, and en ...

What is the method for including HTML special characters in d3.js?

I am attempting to incorporate the degree symbol in my HTML code using ° const degreeNum = d3 .select(`#windBox${order}`) .append("text") .attr("x", 250) .attr("y", 130) .style("font", "bold 50px sans-serif") ...

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

Create an interactive Chart.js displaying real-time data fetched through ajax requests, designed to be fully responsive. Addressing

Chart.js (http://www.chartjs.org/docs/) is the tool I'm using for charting purposes. I am looking to retrieve data from an Ajax request while ensuring that the chart is responsive. Within my HTML markup, I've included a canvas element like this ...

Dynamically change class on scroll using VueJs

Struggling to add and remove a class from the header on scroll without success. The class is currently being added multiple times with each scroll, resulting in duplication. How can I ensure the class is only added once and removed when ScrollY < 100? ...

Moodle version 3.0 is experiencing issues with loading CSS and Javascript due to compatibility issues with NGINX requests not matching the actual paths

Here is my current configuration: Operating System: Ubuntu 14.04 Web Server: Nginx 1.4.6 PHP Version: 5.5.9 Moodle Version: 3.0 After successfully installing Moodle 3.0 through the browser, none of the CSS or JavaScript files are loading. The error logs ...

Fixing issues with Ajax calls in Internet Explorer versions 7 and 8

Here is the Javascript code I have written: $("#login").click(function(){ username=$("#user_name").val(); password=$("#password").val(); $.ajax({ type: "POST", url: "login.php", data: "username="+username+"&passw ...

Different Ways to Incorporate Event Tracking into a JavaScript Alert

My website is quite simple, with just 4 hyperlinks. I'm conducting an experiment on bounce rates and trying to implement an event in a JavaScript alert. The goal is for the event to register when the user clicks "ok" on the alert, thus reducing the bo ...

Leveraging the reset function with the $meteor.object

Currently, I am working on a straightforward controller utilizing the angular-meteor starter project. controller("PartyDetailsCtrl", function($scope, $stateParams, $meteor) { $scope.party = $meteor.object(Parties, $stateParams.partyId); $scope.save = ...

Having trouble with a lengthy formula in your Google Sheets Apps Script function? You may encounter an error like `SyntaxError: missing ) after argument list line: 14 file: new line.gs`. Let

The Apps Script function being discussed: function insertNewRow() { var ss = SpreadsheetApp.openById("redactedforprivacy"); var sheet = ss.getSheetByName("Main"); sheet.insertRowBefore(2); var date = new Date(); var month = date.getMonth() + 1 ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

Adding a modifier to multiple elements within an object

My document structure includes the following: { _id: ..., name: ..., keywords: { group_a: [1, 2, 5], group_b: [4, 7, 6] } } I've figured out how to add elements to one of the elements in the keywords object like this: db.coll.update ...

Corrupted file download after exporting Web API data to Excel

I utilized OfficeOpenXml ExcelPackage to create an excel file from a list of Objects. The download is successful, but upon opening the file, Excel issues a warning that it is corrupted and not saved in the proper file format. I also attempted using FileSav ...

Deleting an item from an array using Vue.js

1. How can I remove a link using the method from a Vue.js component? Please help me troubleshoot this error: 'method splice is undefined' is showing up in console. Adding a link when inserting a message is not an issue, but removing it seems impo ...

Textfield with predictive text suggestions

I am currently working on implementing an autocomplete textfield for my Rails application, following the example from the Agile Web Development with Rails, 3rd Edition. However, when I try to insert their demo code: <%= stylesheet_link_tag &apo ...

The sequencing of operations in Node.js streams

I am having an issue with validating an image before saving it to disk. Currently, I am utilizing the GM library. // Express application implementation app.post('/image', function(req, res) { var stream = gm(req) .size({ bufferStr ...

What is the best way to use JavaScript to conceal all div elements?

Can someone please provide a JavaScript solution to hide all divs on a web page without using jQuery? I am looking for a method that does not involve using the arrays that are associated with document.getElementByTag. If this is not possible, could you p ...

Having trouble importing the hash-set module in TypeScript/SystemJS?

In the midst of developing an Aurelia project with TypeScript to generate JavaScript, I decided to incorporate another custom library called 'hash-set' (installed using jspm install npm:hash-set --save). However, I encountered difficulties in act ...

Utilizing Typescript to filter a table and generate a transformed output for each item

What's the best way to return each mapped element of an array using an optimized approach like this: this.itemsList= res.map( ( x, index ) => { x.id = x.code; x.itemName = x.name; return x; }); I've tried optimizing it with a second me ...