简体   繁体   English

Ember通过HBS模板以编程方式调用控制器操作

[英]Ember programmatically call controller action from hbs template

I have a defined action on my controller that makes a modal visible. 我在控制器上有一个已定义的动作,该动作使模式可见。 In my hbs template, I am able to create a button and assign it the action. 在我的hbs模板中,我可以创建一个按钮并为其分配操作。 When I do this, I can make the modal appear by clicking the button. 当我这样做时,我可以通过单击按钮使模态出现。

I am trying to show the modal (call the controller action) without having to click anything. 我试图显示模态(调用控制器动作),而无需单击任何内容。 Is this possible? 这可能吗? I want the modal to pop up based on a conditional on the model automatically. 我希望根据模型上的条件自动弹出模态。

Theres a pretty straightforward way to do this, just create a computed alias of the model property that you want 有一种非常简单的方法可以执行此操作,只需创建所需模型属性的计算别名即可

// controller
export default Ember.Controller.extend({
  showModal: Ember.computed.alias('model.showModal')
});

// template
{{#if showModal}}
  <p>Showing modal</p>
{{/if}}

that's it 而已

working example: https://ember-twiddle.com/3e86c841e9d7ea54d4febd74b5463fb8?openFiles=controllers.application.js%2C 工作示例: https : //ember-twiddle.com/3e86c841e9d7ea54d4febd74b5463fb8?openFiles=controllers.application.js%2C

You could create a component, add the button to the component and then pass the model and action into the component. 您可以创建一个组件,将按钮添加到该组件,然后将模型和操作传递到该组件。

Then in the component's init lifecycle hook, do your model conditional check and call the passed in action if it's true . 然后,在组件的init生命周期挂钩中,进行模型条件检查,如果为true ,则调用传递的操作。

// some-template.hbs
{{component-with-button
    model=model
    openModal=(action 'openModal')
}}

// components/component-with-button.js
Component.extend({
    init() {
        this._super(...arguments);
        if (this.get('model.conditionalCheck')) {
            this.get('openModal')();
        }
    }
});

From my knowledge, there's no lifecycle hook in a controller which fires every time you visit a specific page. 据我所知,控制器中没有生命周期挂钩,每次访问特定页面时都会触发。 Adding your check to a component guarantees your check will fire each time you visit the page as it will always render the button component. 将支票添加到组件可确保您的支票在您每次访问页面时都会触发,因为它将始终呈现按钮组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM