我正在开发一个angular-node.js应用程序,作为jira的云插件,其中我有一个按钮,点击后会触发发布请求。我面临着一个奇怪的问题,这个帖子请求被称为点击按钮的次数。例如,如果我第一次点击按钮,post请求会被调用一次,如果我再次点击,那就是第二次post请求执行两次,以此类推。一旦我刷新页面,它就会再次从零开始。这是代码:
控制器代码:
$scope.addActor = function(){
AP.require('dialog', function(dialog){
dialog.create({
key: 'actor-content',
width: '40%',
height: '30%',
chrome: true,
});
});
AP.require('events', function(events){
events.on('customEvent', function(){
console.log(arguments[0]);
var data = {
productName: $scope.productName,
checked: false,
actor: arguments[0]
};
$http.post('/addActor', data)
.success(function(data){
$scope.actors = [];
for (var actor in data){
console.log(data[actor].checked)
console.log(data[actor].actor)
$scope.actors.push({
checked : data[actor].checked,
id : data[actor].actor
});
}
AP.require("messages", function(messages){
//create a message
var message = messages.success('','Actor added');
setTimeout(function(){
messages.clear(message);
}, 2000);
});
/*$scope.formData = {};*/
}).error(function(data){
AP.require("messages", function(messages){
//create a message
var message = messages.error('','Error in Adding Actor');
setTimeout(function(){
messages.clear(message);
}, 2000);
});
});
});
});
};
dialogActor.hbs
<body style="background:white">
<div class="aui-dialog2-content">
<script>
$(document).one('click', function(e) {
// initialization here
AP.require('dialog', function(dialog) {
dialog.getButton('submit').bind(function() {
AP.require('events', function(events){
var actor = $('#actor').val();
events.emit('customEvent', actor);
});
dialog.close();
});
dialog.getButton('cancel').bind(function () {
dialog.close();
});
});
});
</script>
<form class="aui" action="#" name="jiraform" id="actorform">
<div class="content">
<div class="field-group">
<label for="summary">Actor<span class="aui-icon icon-required">Required</span></label>
<input type="text" value="" name="actor" id="actor" class="text long-field" data-aui-validation-field data-aui-validation-required="required" required>
<span class="actorError" style="color: #880000"></span>
</div>
</div>
</form>
</div>
</body>
从更改
AP.require('events', function(events){
events.on('customEvent', function(){
})
})
AP.require('events', function(events){
events.once('customEvent', function(){
})
})
解决了问题。这样可以确保事件只发生一次。