Ember.js: Issue with retrieving Binding property results in undefined value

The following code snippet is sourced from the official ember.js introduction:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="ember-0.9.3.js"></script>
<script type="text/javascript">
    var App = Ember.Application.create();

    App.president = Ember.Object.create({
        name: "Barack Obama"
    });

    App.country = Ember.Object.create({
        presidentNameBinding: "App.president.name"
    });

    App.country.get("presidentName");
</script>
</body>
</html>

I attempted to display the result of

App.country.get("presidentName");
by using an alert, but it consistently showed as undefined. Interestingly, when I executed this statement in the Firebug console, it correctly displayed as "Barack Obama".

The documentation mentioned:

Note that bindings don't update immediately. Ember waits until all of your application code has finished running before synchronizing changes.

Could this be why I am unable to retrieve the value of the bound property in the code? What exactly does "application code has finished running" entail?

Answer №1

When working with objects that have bindings like this, it's important to manually trigger the bindings to synchronize using Ember.run.sync():

var App = Ember.Application.create();

App.president = Ember.Object.create({
    name: "Barack Obama"
});

App.country = Ember.Object.create({
    presidentNameBinding: "App.president.name"
});

Ember.run.sync(); // Ensure bindings are synced

alert( App.country.get("presidentName") );

You can view an example in this jsFiddle link: http://jsfiddle.net/ebryn/3Ctns/

Answer №2

To ensure that your code runs smoothly, it is important to incorporate an Observer that triggers after the initial application logic has executed.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/ember-0.9.3.js"></script>
<script type="text/javascript">
    var App = Ember.Application.create();

    App.president = Ember.Object.create({
        name: "Barack Obama"
    });

    App.country = Ember.Object.create({
        presidentNameBinding: "App.president.name"
    });

    App.country.addObserver('presidentName', function() {
        alert(App.country.get("presidentName"));
    });
</script>
</body>
</html>

For more information on implementing Observers, refer to the ember.js introduction.

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

It appears that the use of "window.location" is causing the ajax post

I'm facing an issue with sending data to PHP using AJAX and redirecting to the PHP file. It seems that when I redirect to the PHP file, the data sent through AJAX is not being received. My goal is to have a button click trigger the sending of data to ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

Is there a problem with Framer Motion exit and AnimatePresence in Next.js?

Why isn't my exit prop or AnimatePresence working as expected? This is my custom variant: const imgVariant = { initial: { opacity: 0, y: -100, }, animate: { opacity: 1, y: 0, transition: { type: " ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

Utilizing event delegation for JavaScript addEventListener across multiple elements

How can I use event delegation with addEventListener on multiple elements? I want to trigger a click event on .node, including dynamically added elements. The code I have tried so far gives different results when clicking on .title, .image, or .subtitle. ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

Creating a state in React and populating the rows of a Material-UI table with fixed data

I have implemented a table in the UI using the material-UI Table component. Initially, I added static data without using the state property of react. Now, I am looking for a way to assign static data to table rows by utilizing the state property. The code ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

What is the correct syntax for comparing -1, 0, and 1 in JavaScript?

Is there a way to achieve the functionality of a <=> b in JavaScript? It seems that this operator does not exist. Any suggestions for an equivalent function? Appreciate it, Dorian ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Showcase a sizable picture broken down into smaller sections

I am interested in creating a mapping application similar to Google Maps that can asynchronously load images from the backend. I am seeking guidance on where to begin and how to proceed in this endeavor. The ultimate goal is to have the image displayed w ...

Can you explain the significance of the ColSpan property in the Material UI TablePagination?

Why is ColSpan used in this code snippet? Reference: https://material-ui.com/components/tables/#table Check for the arrow symbol <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, ...

jQuery plugin modifies keypress events

I have integrated the Jquery ImgAreaSelector plugin into my website. Within my site, I have implemented several keypress triggers using jquery. For example: $(document).bind('keypress', 'S', function(){ alert("You have pressed S key ...

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Populate an array of objects with various key-value pairs

In my @change method, I receive the following values: changeAttr(id, key, value) { const selections = []; }, id can be any number, key could be: color, size, sex, etc..., and value could be: red, 8, female, etc. Initially, the values might look like ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

Make sure to wait for the scrollTo function to finish before executing any other commands

I have a sleek scrolling directive in my AngularJS app that automatically scrolls to the bottom of the page. I want this command to execute only after the scrolling has completed. Currently, I trigger the scroll function and then use $('#comment-input ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

The issue arises when attempting to apply a filter to an array, as the variable returns as

After successfully using local state, I encountered an issue with Redux where the component returned undefined. How can I effectively compare two arrays and filter out users who are already in the current users array? import { FETCH_USERS_TO_ADD } from & ...