{{action}} with a click event doesn't trigger the function in the v2 Ember router

最后都变了- 提交于 2019-12-23 02:36:34

问题


I just updated Ember and I am trying to convert an old app to the new router API.

In my template I have this:

<button {{ action "createNewApp" }} class="btn btn-primary">Create application</button>

And I put a createNewApp in my route:

App.CreateAppRoute = Ember.Route.extend({
    renderTemplates: function() {
        this.render({ outlet: 'content'});
    },
    createNewApp: function(){
        console.log("It's clicked");
    }
});

However, when I click on the button the function is never called. I have tried to change the target of the event to the controller but it's still not working. Is this a bug or am I doing something wrong?


回答1:


I was able to handle the click using a function in the events property of the router (thanks sly7_7) or using a function in the controller:

Template:

<script type="text/x-handlebars" data-template-name="application">
    <h1>Content Here:</h1>
    {{outlet content}}
  </script>

  <script type="text/x-handlebars" data-template-name="content-view">
    <h2>content</h2>
    <button {{ action "createNewApp" }} class="btn btn-primary">Create application</button>
  </script>

JS:

var App = Ember.Application.create();

App.CreateAppView = Ember.View.extend({
    templateName: "content-view"    
});
App.CreateAppController = Ember.Controller.extend({
    createNewApp: function(){
        console.log("It's clicked, controller");
    }
});

App.Router.map(function(match) {
  match('/').to('createApp');
});
App.CreateAppRoute = Ember.Route.extend({
    renderTemplates: function() {
        this.render({ outlet: 'content'});
    },
    events: {
        createNewApp: function(){
            console.log("It's clicked, router");
        }
    }
});

When the button is clicked, the console log message is "It's clicked, controller" and when the function in the controller is removed the action is handled by the router, and the console log message is "It's clicked, router". If no target is specified in the {{action}} Ember tries to find the event in the view, then the controller, then the route.

This is using a build of emberjs built today from source.

Original answer below:

The {{action}} in the new router is replaced with {{linkTo}}.

The emberjs.com guides are constantly being updated with new info about the new router. The links guide covers the {{linkTo}} helper, and the actions guide discusses using the {{action}} helper to handle events in templates.



来源:https://stackoverflow.com/questions/14129444/action-with-a-click-event-doesnt-trigger-the-function-in-the-v2-ember-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!