How to pass parameters in emberjs render method?

2019-07-27 03:24发布

问题:

I am trying to pass parameters to a modal view while rendering it. Here is what I got so far:

In my application route, I have:

export default Ember.Route.extend({
  actions: {
    openModal: function(modal, opts) {

      return this.render(modal, {
        into: 'application',
        outlet: 'modal'
        model: function(){ return opts },
        controller: modal
      });
    },
    closeModal: function() {
      return this.disconnectOutlet({
        outlet: 'modal',
        parentView: 'application'
      });
    }
  }
});

I have a general modal view:

import Ember from 'ember';

export default Ember.View.extend({
  tagName: 'div',
  classNames: 'modal'.w(),
  didInsertElement: function() {
    console.log("did insert element");
    this.$().attr('id', 'modal');
    this.$().modal({
      keyboard: false,
      backdrop: 'static'
    });

    return this.$().modal('show');
  },
  willDestroyElement: function() {
    return this.$().modal('hide');
  }
});

and a view specific to my modal:

import ModalView from '../modal';
export default ModalView.extend();

I want 'opts' (passed as an argument in openModal) to be processed so that I can fill the content of the modal depending on it. So far I cannot get anything from my modal controller:

import ModalController from '../modal'

export default ModalController.extend({
  init: function(){
    console.log('initializing modal');
    console.log(this.get('model'));
    console.log(this);
  },
  actions: {
    confirm: function() {
      //alert('OK, it will be done!');
      return this.send('closeModal');
    }
  }
});

What would be the correct way to do this?

回答1:

So I figured it out, there has to be a better to do it but the following should work for me:

Application route:

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    openModal: function(modal, opts) {
      this.controllerFor(modal).set('model', opts);
      return this.render(modal, {
        into: 'application',
        outlet: 'modal'
      });
    },
    closeModal: function() {
      return this.disconnectOutlet({
        outlet: 'modal',
        parentView: 'application'
      });
    }
  }
});

Controller of my modal window:

import ModalController from '../modal'

export default ModalController.extend({
  modalContent: "test",
  actions: {
    confirm: function() {
      //alert('OK, it will be done!');
      return this.send('closeModal');
    }
  },
  idUpdated: function(){
    var id = this.get('model').id;
    console.log(id);
    // Update modal content with the id here
    // Ajax request goes here.

  }.observes("id")
});


回答2:

try to change to:

openModal: function(modal, opts) {

  return this.render(modal, {
    into: 'application',
    outlet: 'modal'
    model: opts, // here
    controller: modal
  });
}