Utilizing controllers to append objects to an array in the model

Hi there, I'm currently working on a project where I need to add an object to an array using Ember. The friends controller model contains an array of objects (App.friends).

In the friends/new template, I collect a user's first name, last name, and some information about them.

Once I have gathered this information, the user clicks "create" and the details are added to App.friends by utilizing the needs feature in Ember to access App.friends from within the FriendsNewController.

However, when I attempt to create the object, I encounter the following error:

Uncaught TypeError: desc.get is not a function

App.FriendsRoute = Ember.Route.extend({
    model: function(){
        return App.friends;
    }
});


App.FriendsNewController = Ember.Controller.extend({
    needs: 'friends',
    isInvalid: true,

    validForm: function(){

        if(this.get('lastName') && this.get('firstName')){
            this.set("isInvalid", false);
        } else {
            this.set("isInvalid", true);
        }

    }.observes('firstName', 'lastName'),

    actions: {
        create: function(){
            var newFriend = Ember.copy(this.content);
                this.get('controllers.friends.model').addObject(newFriend);
            this.transitionToRoute('friends');
        }
    }
});

  <script type="text/x-handlebars" id="friends/new">
    <label>First Name</label>
    {{input value=firstName}}<br />

    <label>Last Name</label>
    {{input value=lastName}}<br />

    <label>About</label>
    {{textarea value=about}}<br />

    <button {{action "create"}} {{bind-attr disabled=isInvalid}}>Create</button>

  </script>

      App.friends = [
    {id: 1, firstName: "John", lastName: "Joe", about: "Funny"},
    {id: 2, firstName: "Mary", lastName: "Joey", about: "Smart"},
    {id: 3, firstName: "Henry", lastName: "Jim", about: "Kind"}
];

I am quite new to Ember, so any guidance or advice would be greatly appreciated. Thank you :)

Answer №1

You're definitely heading in the right direction.

Next, you're attempting to insert an object into a controller:

this.get('controllers.friends').addObject(newFriend);

However, it should actually be inserted into an array:

this.get('controllers.friends.model').addObject(newFriend);

Do you know what App.friends is? In order for addObject to function correctly, it needs to be an Ember Array (not simply a plain array, like [1,2] as opposed to Ember.A([1,2]))

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

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

How can I make JavaScript skip over a specific portion of my HTML code?

I have a script running on all pages of my website. I would like it to continue running on the specific page, but ignore a certain section. For example: <p>process with javascript</p> <p>skip, instruct javascript function to ignore</ ...

Struggling to get JQuery timing events to function properly?

Encountering timing issues with the events in my self-made simon memory game. Experimented with setTimeout but struggling to figure out which events to time and the appropriate duration for them to be distinguishable. $('#play').click(function( ...

The stored information causes the material ui text fields to malfunction

Having trouble with my text fields in a React and Material UI application. When autofill data is saved, the styling breaks. The component code is included below. I've searched online but couldn't find any helpful solutions. import React, { useSta ...

JavaScript is malfunctioning following recent modifications

My JavaScript code is designed to change the z-index of an image when the mouse hovers over it. However, I recently made some changes to the dimensions and positioning in the CSS, causing the script to stop working for the images. To see an example, visit ...

a gentle breeze gathers a multitude of entities rather than items

When utilizing a restful server with node.js and sending a collection of entities wrapped in one entity object (Lookups), everything seems to be functioning properly. However, the issue arises when breeze views the entities in the collection as plain objec ...

Using inline CSS in JavaScript does not seem to function properly

I'm having an issue with this code. I created a javascript variable in the same file and referenced it for setting the background color of the body. However, it's not working as expected. Can someone please explain why and help me achieve my desi ...

Inquire about a term that includes the same letters found in an array

I am encountering an issue. My program needs to prompt me to input a word, with the requirement that the letters of this word must be present in an array. At the moment, I want it to print "The letter is correct" if the letters are contained in the array, ...

Generating a random whole number and assigning it to an element in an array

(HTML5 Canvas, JavaScript) Hey there! I'm facing an issue with my array setup: var chestArray = new Array(9); chestArray[0] = "./assets/chest.png"; var chest = new Image(); chest.onload = function () { ctx ...

What could be causing the network error that keeps occurring when attempting to sign in with Google using React and Firebase?

Having an issue with Google authentication using Firebase. I set up the project on Firebase console and copied the configuration over to my project. Enabled Google sign-in method in the console which was working fine initially. But, after 2 days when I tri ...

JQuery: Implementing automatic selection in a selectbox

Seeking assistance on how to automatically preselect a value in a select box. I am trying to have the select box automatically choose admin aid VI, but my script is not functioning correctly. Can anyone provide guidance on this issue? Here is the HTML co ...

CSS class for Angular drag-and-drop functionality during drag operation

I have implemented the Angular dragdrop functionality in my application. Currently, I am looking to modify the border color of the drop area when an item is being dragged over it. Is there a specific CSS class that I can utilize for achieving this? If no ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

JavaScript for Audio: How to Play Sound

I've been struggling to make this play a sound in Firefox, IE, or Chrome. No matter what I do, it just won't work. <html> <head> <script type="text/javascript"> function playSound() { var audio = document.createElem ...

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

Exploring the Limits with VUE Trailing Path Queries

My goal is to implement an optional query language functionality. When a user visits localhost/#/, the page should automatically redirect to localhost/#/?lang=en (defaulting to English). If the user navigates to /localhost/#/?lang=es, the site will displa ...

Clear all form fields upon successful ajax completion

Struggling to reset all input fields in a form after a successful Ajax request. Take a look at the code below: $.ajax({ type: "POST", url: "form.php", data: datos, success: function() { $(&a ...

Variations between objects?

There are two different methods for using objects in programming. I am curious to understand if the difference lies in the syntax or if there is more to it. Method 1 body(data) = { item1: data.val1; item2: data.val2; item3: data.val3; } Meth ...

Alter the appearance of a webpage dynamically based on the size of the browser window using jQuery or JavaScript

Hey everyone, I've been silently observing for a while now and I'm hoping someone can assist me with a project. I want to create a responsive "3D" cube that flips when hovered over. I've got the cube design nailed down after finding inspira ...