问题
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