Create a duplicate of the sapUI5 JSON model and end the data binding process

I've encountered a similar issue, but the solution doesn't seem to work for me. I have a JSON model named "data" that represents a SAPUi5 form with comboboxes. My goal is to capture the initial state of the model when the application is first opened and preserve it. Then, I want to use this preserved state to reset the form and restore the comboboxes to their default values. At the beginning of my application:

this.getView().setModel(new JSONModel(data)); //initialize the original model

//copy the original model (global variable copyModel)
copyModel = $.extend({}, data); 

Everything seems to be functioning correctly up to this point. Both models are identical. Next, I have a button triggering a reset function:

resetP: function(){

     this.getView().setModel(new JSONModel(copyModel));
     console.log(copyModel);
     }

The first time I make a selection in the comboboxes, then click the reset button to run the reset function, the copyModel reflects the correct data. The same goes for the original data model. However, upon changing the selected value in the comboboxes again, the copyModel starts to adopt the new selection instead. It appears to be getting overwritten somehow. I'm unsure of what mistake I might be making here. Any suggestions? I also attempted using JSON.stringify instead of extend.

Answer №1

When working with JSON models, two-way binding is the default behavior. This means that when events like selectionChange are triggered on a ComboBox, the data in the model is continually updated. Since JavaScript uses objects by reference, it is the original copyModel object that gets updated.

To prevent this, you can set a copy of the copyModel to the JSON model.

Additionally, avoid repeatedly setting the entire model again and again. Instead, simply update the data within the model and then refresh the model itself. There are two ways to do this:

a.

resetP: function(){
                this.getView().getModel().setData(copyModel);
                console.log(copyModel);
            }

b. Alternatively, you can update the required property and then call:

this.getView().getModel().updateBindings();

Answer №2

To achieve an independent copy of an object, we utilize

jQuery.extend(true, {}, object_to_copy);
in this manner to generate a "deep copy."

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

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Issue with bouncing dropdown menu

I am in the process of enhancing a Wordpress website by implementing a jQuery menu with sub-menus. Below is the jQuery code snippet: $(document).ready(function(){ $('.menu > li').hover(function(){ var position = $(this).position(); ...

Tips for establishing a connection to a proxy server and executing an http.request through the proxy using nodejs

I'm looking to establish a connection to a proxy in order to send http requests through it. For instance: proxy.connect(someip:someport,function(){ console.log('[PM]['+this._account+'] Logging in..'); var auth_re = /auth& ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

Submitting the form with an extending controller results in an undefined state

I have a primary controller and another controller where I extend the primary one to display a different layout. Primary controller: function CustomerInformationController(...) { var vm = this; ... vm.save = function() { if (angular. ...

Transitioning JS/CSS effects when the window is inactive

My latest project involved creating a small slider using JavaScript to set classes every X seconds, with animation done through CSS Transition. However, I noticed that when the window is inactive (such as if you switch to another tab) and then return, the ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

Making an AJAX POST request using jQuery to send the current date and time to an ASP

I am working with an ASP.NET Web API endpoint where I need to send POST data. Suppose I want to post the following information: var myObject = { name: "Alice Johnson", age: "29", accountCreated: "CURRENT DATE TIME" }; What is the JavaScript equivalent o ...

What is the best way to display a Bootstrap alert above all other elements on the page?

I need help with adjusting the placement of my bootstrap alert. Currently, when the input box value is not valid and the button is clicked, the alert shows up below the input box. I would like it to appear in the middle of the page, on top of the text box. ...

The image is not appearing in my small AngularJS application

I have developed a small application that converts Fahrenheit to Celsius and I am trying to display a relevant image based on the Fahrenheit temperature input. However, I am facing difficulties in getting the image to display correctly. Can someone please ...

Unable to log out when the button is clicked

I am having trouble figuring out why I can't log out when clicking the button. I have a logout button in my header (navigation). My experience with React is limited. Within my project folder, I have a Store directory which contains an Auth-context f ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Tips for directing the scroll according to the current selection class

I am attempting to focus the scroll based on the selected class when clicking on the previous and next buttons. How can I achieve this functionality? Please review my code on https://jsfiddle.net/kannankds/bcszkqLu/ <ul class="kds"> <li>tile ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

What are some ways to postpone the execution of a function in React or NextJs?

How do I automatically redirect to the home page after 5 seconds of accessing a page in NextJS? I attempted to achieve this using the following code: useEffect(() => { const timer = setTimeout(() => { redirect('/home') ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

Sending a POST request using PHP CURL with an empty value in the data

I have tried using this code to send data via POST request to a specific URL. The content-type header is set as text/html. file_get_contents("php://input"); The code appears to be successfully sending the data, however, the values are not being received a ...