Unlocking the Controller Action: Navigating from a Component Controller in Ember

I am currently trying to enhance the functionality of an Ember component. The specific component I am working on is located here:

app / templates / programmers.hbs

{{echo-hlabel-tf 
   id= "id-test-hlabel"
   class="class-test-hlabel-mio"
   label="Horizontal textfield"
   textValue="..."
   regExp="^([a-z0-9]{5})$"
   errorMsg="Text hasn't five characters"
   fnActionButtonClicked = "sayHello"
}}

I am experimenting with the parameter 'fnActionButtonClicked'. This parameter references a function that is executed, but it is not integrated within the component's functionality (like passing a JavaScript function as a parameter). As someone new to Ember, I am uncertain about the best approach to handle this. The template for the component can be found here:

app / templates / components / echo-hlabel-tf.hbs

<div id="echo-hlabel-tf">
    <span id="{{id}}-echo-hlabel-tf-label" 
          class="{{class}}-echo-hlabel-tf-hlabel">
    {{label}}
</span>
<span id="{{id}}-echo-hlabel-tf-value" 
      class="{{class}}-echo-hlabel-tf-value">
    {{input id='input-id' class='input-class' value=textValue
            focus-out = (action 'validateRegExp' textValue regExp) 
    }}
</span>
<span id="{{id}}-echo-hlabel-tf-error-msg" 
 class="{{class}}-echo-hlabel-tf-error-msg">
    <p id='error-msg' class="error-msg">
        {{errorMsg}}
    </p>
</span>

<div>
    <h2>Testing passing functions to the component</h2>
        <input type="button" {{action "actionButtonClicked"}}/>
</div>
</div>

Within the template, you will find an input type="button" connected to "actionButtonClicked" at the end. The controller for the component is located here:

app / components / echo-hlabel-tf.js

import Ember from 'ember';

export default Ember.Component.extend({
   classNameBindings:['error'],
   error:false,

   actions: {
    validateRegExp(text,regExpStr,event){
        let regExpObj = new RegExp(regExpStr)
        if(regExpObj.test(text)){
            this.set('error',false);
        }else{
            this.set('error',true);
        }
    },
    actionButtonClicked(){
        console.log('Arrives to the component');
        var action = this.get('fnActionButtonClicked');
        console.log(action);
        // How can I call the function in another controller
        // With parameter fnActionButtonClicked name
    }
 }
});

As seen, the parameter in the template 'fnActionButtonClicked' (sayHello) will be accessed in actionButtonClicked() via var action = this.get('fnActionButtonClicked');.

This brings me to my question. Since I cannot pass a JavaScript function as a parameter of a template (or at least, I believe it's not the recommended approach), I have created a controller named 'sampleController' to define the action 'sayHello' (as specified by the fnActionButtonClicked value) using the following code:

app / controllers / sample-controller.js

import Ember from 'ember';

export default Ember.Controller.extend({
   actions:{
    sayHello(){
        console.log("I'm saying hello this time");
    }
  }

});

How can I, from app / components / echo-hlabel-tf.js:actionButtonClicked(), execute the code in app / controllers / sample-controller.js : sayHello()? Is there a way to access another controller from the component controller? Am I taking the right approach in Ember to achieve my objective?

Thank you in advance.

Answer №1

Instead of using sample-controller.js, it is recommended to create a controller specifically for the route programmers. Therefore, please create a new file called app/controllers/programmers.js.

export default Ember.Controller.extend({
  actions:{
    sayHello(){
      console.log("I'm saying hello this time");
    }
  }
})

In addition, make sure to include the following code inside the component app/components/echo-hlabel-tf.js.

actionButtonClicked(){
  console.log('Arrives to the component');
  this.sendAction('fnActionButtonClicked');        
}

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 mysterious Vue.js and Nuxt.js custom element

Encountering an issue https://i.sstatic.net/imRbe.png Seeking assistance with identifying my mistake. Attempting to create reusable components, starting with a button for example. I have created it in the file path: /components/MusicPlayer.vue: <temp ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

Tips for employing numerous if-else conditions utilizing the ternary operator in jsonpath-plus?

JSON { "customer":{ "address":{ "stateRegion":"", "stateRegionCode":"" } } } Code "address.state_code": "$.customer.address.[stateRegion ? state ...

Saving a variable within a for loop in JavaScript

Hey everyone, I could really use your help right now. Here's the code block I'm struggling with: function readyToSubmit(answerPack, answerArr, len) { for (var i = 0; i < answerArr.length; i++) { var questionId = answerArr[i].id; con ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Insert half a million records into a database table using JavaScript seamlessly without causing the webpage to crash

I am facing an issue with my report system where running a single report query results in over 500,000 rows being returned. The process of retrieving the data via AJAX takes some time, but the real problem arises when the browser freezes while adding the H ...

JavaScript, specifically in the VueJS framework, consistently defaults to utilizing the final value within a

Describing my issue, I am using a for loop to extract elements from an array and assign them to a JSON value. It looks something like this: hotel={ rooms: 2, price: [ 100, 200 ], occupation: [ '1 child', '1 adult' ] I aim to push thi ...

Relocating scripts that have already been loaded

When using AJAX to load a page, the entire content including <html>, <head>, <body> is loaded. This means that all scripts meant to run on page load will be called. However, sometimes the browser may remember that certain scripts have alr ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

Angular JS causing text alignment issues in table cells when viewed on mobile devices

I have created a web application that requires both desktop and mobile views, utilizing Angular JS. Everything is functioning as expected except for the text alignment within tables. I attempted using <td align="left">, but it did not produce any cha ...

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

In JavaScript, the Else statement fails to run

Hi there, I'm currently working on creating a function to check the validity of a string input. This is what I have so far: function validatePassword(){ passW = prompt ("Enter Password:"); if (passW == 'Pass123'){ document.write ('Y ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

`Three.js and its efficient use of JavaScript for enhancing performance``

Deep within the Object3D code lies: rotateX: function () { var v1 = new THREE.Vector3( 1, 0, 0 ); return function ( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), But what about: rotateX: function (angle) { var v1 = new ...

What is the process for programmatically aligning two cards side by side using Material UI in React after retrieving data from an API?

I am currently working with data from an API that I need to display in the format of cards, arranged side by side. To achieve this, I have been using an array and passing the data to components programmatically. You can see the output image and my code bel ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Transmit JSON information using jQuery

Can you explain why the code below is sending data as City=Moscow&Age=25 instead of in JSON format? var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'js ...