我无法从 Post.success 函数内部调用 this.RenderDeals() 。我认为这与范围有关?有人可以阐明这个问题,并可能提出解决方法。我尝试过使用原型(prototype)和模块模式,但都没有成功。
FYI Post 是一个 $.ajax 包装器,返回 jQuery Deferred 对象。
function Deals() {
this.template = '#trTemplate';
this.container = '#containerTable';
this.GetDeals = function () {
Post('Deal.svc/GetDeals')
.success(function (result) {
this.RenderDeals(result);
});
};
this.RenderDeals = function (deals) {
$(this.template).tmpl(deals).appendTo(this.container);
}
}
var deal = new Deals();
deal.GetDeals();
更新:
好的,所以我在 GetDeals 函数上方添加了以下行:
var me = this;
而是调用
me.RenderDeals(result);
似乎工作正常,但我不确定为什么。
最佳答案
“成功”函数中的 this
引用几乎肯定不是您想象的那样。尝试这个改变:
function Deals() {
var instance = this;
this.template = '#trTemplate';
this.container = '#containerTable';
this.GetDeals = function () {
Post('Deal.svc/GetDeals')
.success(function (result) {
instance.RenderDeals(result);
});
};
this.RenderDeals = function (deals) {
$(this.template).tmpl(deals).appendTo(this.container);
}
}
通过在“instance”变量中存储对 this
的引用,您的处理程序将在调用其他函数(“RenderDeals”)时有保证返回到相关实例的方式。
关于JavaScript 类范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358901/