javascript 如何以编程方式触发操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18850340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I trigger an action programmatically?
提问by Flavio Copes
I have this view
我有这个看法
App.ApplicationView = Em.View.extend({
templateName: 'application',
actions: {
myAction: function() {
//
}
}
});
Suppose I want to trigger manually that action from another view method, such as didInsertElement, like:
假设我想从另一个视图方法手动触发该操作,例如 didInsertElement,例如:
App.ApplicationView = Em.View.extend({
templateName: 'application',
actions: {
sidebarShowHome: function() {
this.set('sidebarIsHome', true);
this.set('sidebarIsNotifications', false);
this.set('sidebarIsArchive', false);
},
},
didInsertElement: function() {
this.actions.sidebarShowHome();
}
});
How could I do it? this.actions is undefined from within a view method.
我怎么能做到?this.actions 在视图方法中是未定义的。
采纳答案by intuitivepixel
You can use the TargetActionSupportmixin along with this.triggerAction:
您可以将TargetActionSupportmixin 与 一起使用this.triggerAction:
App.ApplicationView = Ember.View.extend(Ember.TargetActionSupport, {
templateName: 'application',
actions: {
myAction: function() {
console.log('myAction');
}
},
didInsertElement: function() {
this.triggerAction({
action:'myAction',
target: this
});
}
});
By default using this.triggerAction()without parameters will send the action to the controller, however if you need to target a different destination define the targetoption as shown in the example.
默认情况下使用this.triggerAction()不带参数会将动作发送到控制器,但是如果您需要定位不同的目标,请定义该target选项,如示例所示。
Working demo.
工作演示。
Hope it helps.
希望能帮助到你。
回答by Nelu
To call an action in the same controlleryou can use send.
要在同一控制器中调用操作,您可以使用send.
this.send('nameOfAction', someParams);
To call an action in the parent controllerfrom a component use sendAction.
要从组件调用父控制器中的操作,请使用sendAction.
this.sendAction('nameOfAction', someParams);
回答by vanthome
The triggerAction()method only exists, if the view uses the Ember.TargetActionSupportmixin. If this is not the case, use this.get('controller').send('action');instead.
该triggerAction()方法仅存在,如果视图使用Ember.TargetActionSupportmixin。如果不是这种情况,请this.get('controller').send('action');改用。

