How to Get and Show Updated Domain Model in Metawidgets (JavaScript) within the Client?

149 Views Asked by At

I'm using Metawidgets for javascript, and want to access and show the updated domain model if any changes were made to it, without routing back to a server (e.g.: all within the same client side javascript). Sadly, every example I could find went back to the server or plugged into a framework.

Here's an example showing my problem with getting the updated model. Change the values on the page, click on 'display' and check out the console window. Notice how it still shows the old values.

<!DOCTYPE html>
<html>
<head>
   <script src="metawidget-4.1/js/lib/metawidget/core/metawidget-core.min.js" type="text/javascript"></script>
 </head>
 <body style="font-family:Arial">
    <div id="metawidget"></div>
    <script type="text/javascript">
        var mw = new metawidget.Metawidget( document.getElementById( 'metawidget' ) );
        mw.toInspect = {
            name: 'X',
            age: 40,
            display: function(x) {
                // This never shows the updated model if the user changes values
                console.log(this);
            }
        };
        mw.buildWidgets();
    </script>
</body>
</html>

How can I get Metawidget to automatically display an updated version of the domain object if it's changed from the code? For instance, if I were to increment the age (e.g: person.age++ or this.age++ from within display), the page doesn't automatically reflect this.

1

There are 1 best solutions below

3
On BEST ANSWER

You're asking two questions here. I'll answer them separately.

  1. How do I get Metawidget to save the values back from the widgets into the domain object? To do this, your code should look like:

       display: function(x) {
            mw.save();
            console.log(this);
        }
    
  2. How do I get Metawidget to redraw the widgets with new values? To do this, your code should look like:

       display: function(x) {
            this.age++;
            mw.buildWidgets();
        }
    

However, I should say the way you've written this code is a bit strange. It's fine if it's just a quick example for learning purposes, but in production code you would want to decouple things.

For example, you wouldn't typically define the .toInspect inline, and have functions on it that directly reference the mw.