Effective Binding of Ember.js Controllers and Views (Doing it the Ember.js Style!)

Please forgive the length of this question, as I struggled to condense it.

My current challenge lies in understanding the interplay between a controller and its view within Ember.js. Specifically, I am grappling with the concept of controller property and view bindings. While my application is functional, I sense that the approach I have taken may not align with the preferred 'Ember.js' methodology.

Key details to note: My project follows the directory/file structure suggested in the guides/documentation. It operates within a sinatra application environment. Despite being a work in progress, the application behaves as expected thus far.

Although incomplete, here's a high-level overview of what I aim to achieve:

1) Upon visiting the root URL '/', users are directed to '/locate'.

2) The LocateController fetches the user's location and populates form fields with latitude/longitude data.

3) Upon submitting the form via AJAX POST to the sinatra '/locate' route...

(request processed by server)

4) Users are then redirected to the ember.js '#/located' route.

5) JSON response from the server is displayed.

I've only implemented step one thus far. While the form can be manually submitted, the goal is for an automatic submission.

The locate view correctly populates the form fields. However, achieving this using jQuery directly doesn't seem consistent with proper Ember.js practices.

Below are select code snippets:

Snippet of slim views:

... // Omitted for brevity

Snippet from applicationView.js:

... // Omitted for brevity

Snippet from applicationController.js:

... // Omitted for brevity

Snippet from router.js:

... // Omitted for brevity

While I have consulted the Ember.js Guides, API Documentation, and GitHub repository, I still struggle to grasp the implementation of computed properties for latitude and longitude attributes.
Additionally, I acknowledge that there might be a more efficient way to handle data transfer to the server (e.g., JSON or ember-data), but for now, I prefer solutions that won't require significant backend restructuring. Your insights and guidance on these matters would be appreciated. Thank you for your time and consideration amidst this lengthy query.

Answer №1

Agreed, setting input values with jQuery in an Ember app is not recommended. It's best to leverage Ember's property binding capabilities for a more efficient approach. Instead of directly setting the input values, consider moving the getLocation logic to the LocateController or incorporating it within the route setupController hook (refer to setupController example here). You can also define these properties on your App instance if needed.

Rather than:

var GeoLocation;

GeoLocation = (function(location){
    $('#latitude').val(location.coords.latitude),
    $('#longitude').val(location.coords.longitude)
});

navigator.geolocation.getCurrentPosition(GeoLocation)

It's advisable to handle this in the route:

App.LocateRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    navigator.geolocation.getCurrentPosition(controller.geoLocation)
  }
});

App.LocateController = Ember.Controller.extend({
  geoLocation: function(location){
    this.set('latitude', location.coords.latitude);
    this.set('longitude', location.coords.longitude);
  }
});

Now, the Locate controller has 'latitude' and 'longitude' properties defined which can be bound to in your template. You may also set these properties on your App instance for global access, adjusting the bindings accordingly to 'App.longitude' and 'App.latitude'.

App.LocateController = Ember.Controller.extend({
  geoLocation: function(location){
    Ember.set(App, 'latitude', location.coords.latitude);
    Ember.set(App, 'longitude', location.coords.longitude);
  }
});

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 custom event handler for form input changes using React hooks

A unique React hook was created specifically for managing form elements. This hook provides access to the current state of form fields and a factory for generating change handlers. While it works seamlessly with text inputs, there is a need to modify the c ...

Error encountered in Jest (a testing tool for React) - Parse Error: Line 1 contains an invalid import declaration

Currently, I am utilizing node.js version 0.10.x and jest version 0.4.x to conduct tests on react.js. Prior to testing my react components, I was utilizing node.js version 0.12.x. I switched to version 0.10.x using nvm. I proceeded to rebuild all modules ...

What is the best way to allocate Json to the Editor within drafjs?

Within a JSON object, I am attempting to assign text to a DraftJS editor. However, I encountered an error when trying to do so: "PageContainer.js:165 Uncaught TypeError: draft_js__WEBPACK_IMPORTED_MODULE_1__.EditorState.createFromText is not a function" ...

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

Ways to constrain checkbox choices to only one within an HTML file as the checklist with the checkboxes is being created by JavaScript

I am working on developing an HTML dialogue box to serve as a settings page for my program. Within this settings page, users can create a list of salespeople that can be later selected from a drop-down menu. My current objective is to incorporate a checkbo ...

TypeScript Redux actions not returning expected type

Basically, I am attempting to assign types to a group of functions and then match them in my Redux reducer. Here are the functions I have defined in actions.ts: export const SET_CART_ITEMS = "SET_CART_ITEMS"; export const SET_CART_TOTALS = "SET_CART_TOTA ...

Troubleshooting a malfunctioning PHP form that uses jQuery and AJAX

Snippet of HTML code: <form class="contact_form" action="" name="contact_form"> <ul><li> <input type="email" name="email" placeholder="Please enter your email here" required /> </li><li> <button class="submit" type=" ...

Accessing the setter's name from within a Javascript setter function

Can anyone help me figure out how to get the name of the setter that is called when assigning a value? Here's an example: var b = {}; var a = { set hey(value) { b[<name of setter>] = value; } } I would like to retrieve the name of the set ...

Having trouble retrieving base64 image data from a textarea upon submitting the form for the second time through ajax

My issue involves receiving image data in base64 format from a hidden textarea and saving that value through an AJAX call. The first time I submit the form using AJAX, an image is generated and a new image URL is displayed on success. However, when I try t ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Creating dynamic templates and embellishments in VUE

My VUE components, including Field and Form, are able to dynamically render a form based on the provided data. <template> <form @submit="$emit('submit', $event)" > <template v-for="(item, index) in form.elemen ...

"I need assistance with loading a shader from an external file using THREE.FileLoader. Can you

Can someone help me with loading shaders from an external file in Three.js? The shader works fine when placed within a <script> tag, but I'm encountering issues when trying to load it externally. Here's what I'm doing: var loader = ne ...

Tips on retrieving specific information from PHP through jQuery AJAX

I have encountered an issue with my JavaScript file where I am sending an array of data to my PHP file. The problem is, when trying to print the name in #NAME and password in #PASSWORD, both values end up in both fields. You can see how it currently displa ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

Error Loading Collada Texture: Three.js Cross Origin Issue

I'm encountering an issue with loading a Collada file using three.js that has a texture called Texture_0.png associated with it. The Collada file and the texture are stored in the same blob and accessed via a REST Web Service. CORS is enabled, allowin ...

Utilizing ESLint to Conditionally Import External Packages

I'm attempting to bring in a package and utilize it within my Vue application like so: import ExternalSamplePackage from 'external-sample-package' export default { directives: { ExternalSamplePackage } } Since I am in SSR mode, I want ...

Exploring the art of labeling regions within AngularJS with UI-Router

Recently, I made the switch from using ng.router to ui.router in my AngularJS application. While configuring states in my app, I encountered an issue with state names. It seems that when I include a '.' character in the state name, the routing d ...

Submit the form using AJAX because columns are not permitted

Currently, I have designed a form dedicated to managing the notification recipients for an additional web application. The process is quite straightforward: users are added or removed from receiving notifications. In the removal section, there is a jQuery ...

What is the best way to transfer JSON data between jQuery.dataTables 1.10 and an ASP.NET WebMethod backend?

With Version 1.10 of jQuery DataTables, there have been significant changes from previous versions in how Ajax requests and responses are handled. It appears that the developers of this library lack experience working with an ASP.NET backend. Despite prev ...