简体   繁体   English

从Ember中的组件发送动作

[英]sending actions from within a component in Ember

I'm trying to figure out how to handle in a single place a "login" action, that must be activated from a button click and "enter" keypress; 我试图弄清楚如何在一个地方处理“登录”操作,该操作必须通过单击按钮和“输入”按键来激活。

in my template I've wrapped everything inside a "login-functions" component 在我的模板中,我将所有内容包装在“登录功能”组件中

//template home.hbs
{{#login-functions}}     
    <input id="email" type="email" class="validate">
    <input id="password" type="password" class="validate">

    <div id="login" {{action "login"}}>     
{{/login-functions}}


//component components/login-functions.js
export default Ember.Component.extend({
    actions: {
        login: function() {
            var email = $('#email').val();
            var password = $('#password').val();
            var self = this;

            Utils.login(email, password).done(function(res) {
                localStorage.setItem('Access-Token', res.data.token);
                localStorage.setItem('userId', res.data.user_id);
                self.transitionToRoute('feed');
            })
            .error(function(error) {
                //handle error
            });
        }
    },

    keyPress: function(event) {
        if (event.charCode === 13) {
            console.log('login attempt');
            this.send('login');            
        }
    }
});

But this doesn't work because the action is not sent from the template button to the component's action and also because from the component I can't perform the transition. 但这是行不通的,因为操作没有从模板按钮发送到组件的操作,也因为我无法从组件执行转换。

Can someone tell the best way to handle this? 有人可以告诉最好的方法来解决这个问题吗?

I think it's because your button is part of your home template. 我认为这是因为您的按钮是home模板的一部分。 Maybe the form should be moved in your login-functions template and be called from your home template by doing {{login-functions}} . 也许应该将表单移至login-functions模板中,并通过执行{{login-functions}}home模板中调用该表单。

And for the redirection, components can't do them, I'd suggest to call an action using this.sendAction('didLogin') and handle the redirection in your HomeController . 对于重定向,组件无法执行重定向,我建议使用this.sendAction('didLogin')调用操作并在HomeController处理重定向。

Move the keyPress functions out of the actions. keyPress功能移出动作。

Updated --- Here is a working demo 更新---这是一个有效的演示

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

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