mardi 31 mai 2016

Create a controller event listened to by a component

I'm playing with ideas for making a drag and drop interface. I have multiple components that can be dragged into position over a grid. I will have a button that will allow the user to select different arrangements.

I want a function on the component that sets its position (quite simply with left and top). I want to be able to call this function when the component is inserted, and when a different arrangement is selected.

What I want to do is create an event in the route's controller. I then want each component to be able to listen for the event, and react as necessary. I'm afraid I don't understand enough to make this work. I've read the API, and a couple of questions on here (1, 2), but no luck.

Here's what I have...

The route's controller:

import Ember from 'ember';    
export default Ember.Controller.extend(Ember.Evented, {
    actions: {

        callPosition: function(){
            this.trigger('position');
            console.log('Trigger set...');
        },
})

And the component:

import Ember from 'ember';
export default Ember.Component.extend(Ember.Evented, {

    didInsertElement : function(){
        this.get('controller').on('position', this, this.position);
    },

    position: function(){
        console.log('event heard by the component');
    },

A few things I don't understand:

  1. Have I added the Ember.Evented mixin correctly?
  2. I've added the listener in the didInsetElement event as per the example. Is this the correct way to ensure the component will listen for the event throughout its lifetime?
  3. What's the scope of the event? Can it only be listened for so long at we 'get' the controller that set it?

Your advice is a great help to this budding amateur!




Aucun commentaire:

Enregistrer un commentaire