gpt4 book ai didi

javascript - 将其绑定(bind)到backbone.js 中的 jQuery 回调中

转载 作者:行者123 更新时间:2023-12-01 02:22:33 26 4
gpt4 key购买 nike

我在backbone.js 项目中遇到this 问题。

这是我的观点:

app.SomeView = Backbone.View.extend({
render: function() {
var that = this;
$.getJSON(someURL, function(result) {
that.property = result.something;
});

return this;
}
})

令人费解的是,在 getJSON 回调中 that.property 被设置,但是一旦该函数完成 - 即在 return this - that.property 等于 undefined,与 this.property 相同。

我做错了什么?

最佳答案

不确定为什么您不使用模型。回答你的问题,有不同的解决方案,第一个:

使用事件:

app.SomeView = Backbone.View.extend({
render: function() {
var that = this;
$.getJSON(someURL, function(result) {
that.property = result.something;
that.trigger('DataLoaded', that);
});

return this;
}
});
var view = new app.SomeView();
view.on('DataLoaded', function(theView){
console.log( theView );
});

第二个,您需要添加回调并传递它:

app.SomeView = Backbone.View.extend({

render: function(callback) {
var that = this;
$.getJSON(someURL, function(result) {
that.property = result.something;
callback(that);
});
return this;
}
});
var view = new app.SomeView();
view.render( function(theView){
console.log( theView );
});

我的答案是为了解决您创建的问题而编写的。但为了长期改进,您是否知道模型有一个 fetch 方法,该方法基本上从服务器加载 JSON 并将其与模型关联? http://backbonejs.org/#Model-fetch这就是我加载 JSON 的方式:

app.SomeModel = Backbone.Model.extend({
urlRoot : someURL
});
app.SomeView = Backbone.View.extend({
initialize : function(){
this.model.on('change', this.render);
},
render: function() {
console.log( this.model.toJSON() );
return this;
}
});
var view = new app.SomeView(new app.SomeModel());
view.model.fetch();

关于javascript - 将其绑定(bind)到backbone.js 中的 jQuery 回调中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11991307/

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