抱歉,这个noobie问题,但是我一直在搜索有关shadowing variable的所有现有答案,但仍然无法使我的代码正常工作
export default Ember.ArrayController.extend({
actions: {
generateInvoice: function() {
var amount1; // declare a variable
var amount2;
this.store.find('product', 1).then(function(obj){
amount1 = 100; //assign value to the amount variable
});
this.store.find('product', 2).then(function(obj){
amount2 = 200;
});
console.log(amount1); // undefined!
console.log(amount2); // undefined!
$.post('http://nzud.co.nz/invoice',{
foo1: amount1, //access variable amount ---doesn't work!!
foo2: amount2
} ).done(function(data){
alert("success!");
})
}
}
});
我已经尝试了很多方法,但是仍然无法将模型记录属性存储到变量中并无法从$.post
有效负载中访问
要继续使用变量new值,您必须将代码放入promisse内then
。然后它将起作用:
export default Ember.ArrayController.extend({
actions: {
generateInvoice: function() {
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount
}).done(function(data){
alert("success!");
})
});
}
}
});
发生这种情况是因为该方法find
是异步的,因此您必须在回调函数(本例中为)中处理其结果then
。内的所有内容generateInvoice
范围将(可能)在您之前调用find
方法请求结束的,即使叫里面的第一种方法。
更新:
使用的这两种find
方法product, 1
,我没有得到您的意思,但是:
如果在发送给帖子的请求中有两个值,则应find()
仅使用一次该方法:
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount,
bar: another_value
})
});
或者,如果必须调用两种不同的find
方法,则必须将它们链接起来:
this.store.find('product', 1).then(function(obj){
var amount = 100; //assign value to the amount variable
this.store.find('product', 1).then(function(obj){
var another_amount = 100; //assign value to the amount variable
$.post('http://nzud.co.nz/invoice',{
foo: amount,
bar: another_amount
})
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句