gpt4 book ai didi

javascript - 将 _this 传递给 ajax 调用

转载 作者:行者123 更新时间:2023-11-30 18:06:48 25 4
gpt4 key购买 nike

所以我不确定最好的方法是什么,目前我有一个看起来像这样的 ajax 调用

var _this = this;

_.each(this.models, function (model) {

model.fetch({
success: function(model, response) {
if (_.has(model.attributes, "settings")) {
_this.populateSettings(_this);
}
}

在 populateSettings 方法中,我需要此 Backbone View 的某些属性。我不确定如何获取这些属性,除非传入每个特定属性,或者传入对该主干 View 的引用,然后在 populateSettings 中使用该引用来填充 View 。有一个更好的方法吗?谢谢。

最佳答案

一种选择是在您的 View 中监听 model 上的 sync 事件,以便每当 model 成功与来自服务器,您的 View 可以运行 populateSettings

这看起来像这样:

model.on('sync', this.populateSettings, this)

注意第三个参数,this。传递 this 作为第三个参数设置事件处理程序将在其中运行的上下文。来自Backbone.js文档:

To supply a context value for this when the callback is invoked, pass the optional third argument: model.on('change', this.render, this)

如果您使用这样的事件监听器,则可以完全删除 success: 选项。您可能还会发现 changechange:[attribute] 事件也很有用。

关于javascript - 将 _this 传递给 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15629063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com