Javascript依赖注入和承诺
我试图在JS中传递一个对象(抛出一些jQuery)。:) 运行Javascript依赖注入和承诺,javascript,jquery,Javascript,Jquery,我试图在JS中传递一个对象(抛出一些jQuery)。:) 运行promise.success函数后,我想调用FlappyBarHelper.getUserPropertyCount()方法。我已尝试将此.FlappyBarHelper传递给: return $.ajax({ type: "GET", url: 'get-the-score', flappy: this.FlappyBarHelper,
promise.success
函数后,我想调用FlappyBarHelper.getUserPropertyCount()
方法。我已尝试将此.FlappyBarHelper
传递给:
return $.ajax({
type: "GET",
url: 'get-the-score',
flappy: this.FlappyBarHelper,
});
但是,这仍然使得flappy
在promise.success中没有定义
我的全部代码是:
function Rating(FlappyBarHelper) {
this.FlappyBarHelper = FlappyBarHelper;
}
Rating.prototype.attachRaty = function(property_id)
{
var promise = this.getPropertyScoreAjax(property_id);
promise.success(function (data) {
$('#'+property_id).raty({
click: function (score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
})
.done(function (msg) {
$('#extruderTop').openMbExtruder(true);
//**** FlappyBarHelper is undefined at this point ****///
FlappyBarHelper.getUserPropertyCount('.flap');
});
}
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id)
{
return $.ajax({
type: "GET",
url: 'get-the-score',
});
}
阅读($.ajax]()的文档
所有回调中的this引用是在设置中传递给$.ajax的上下文选项中的对象;如果未指定上下文,则这是对ajax设置本身的引用
因此,应在执行多重调用时传递变量:
Rating.prototype.attachRaty = function(property_id){
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
// use proxy to keep context when the click will be received
click: $.proxy(function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// here it should be defined
this.FlappyBarHelper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
});
}
你也可以考虑做一个闭包变量:< /P>
Rating.prototype.attachRaty = function(property_id){
// here is the closure variable
var helper = this.FlappyBarHelper;
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
click: function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score'
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// you can still use the defined variable: power (and danger) of closures
helper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score'
});
}
漂亮的教科书式答案。谢谢你的详细解释。我还读了关于“成功与完成”的区别:)