gpt4 book ai didi

javascript - 动态改变 Backbone 模型

转载 作者:行者123 更新时间:2023-12-03 11:31:42 24 4
gpt4 key购买 nike

这是我的问题,我想动态更改我的模型(在实例化集合时动态更改模型中的变量)。

这是我的代码:

define(['backbone'], function (backbone) {

var MyModel = Backbone.Model.extend({
initialize: function() {
var that = this;
var likes;
var UrlGetLike = "https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27https://www.facebook.com/pages/Stackoverflow/1462865420609264%27&format=json";
$.getJSON( UrlGetLike, {
format: "json"
})
.done(function(data) {
likes = data[0].like_count;
that.set({
'likes' : likes
});
});
},
});
return MyModel;
});

但是数据没有更新,MyModel 在 .done() 完成之前返回..

我也尝试一下:

define(['backbone'], function (backbone) {

var MyModel = Backbone.Model.extend({
initialize: function() {
var that = this;
var likes;
var UrlGetLike = "https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27https://www.facebook.com/pages/Stackoverflow/1462865420609264%27&format=json";
$.getJSON( UrlGetLike, {
format: "json"
})
.done(function(data) {
likes = data[0].like_count;
that.set({
'likes' : likes
});
that.returnn;
});
},
returnn: function(){
return this;
}
});
});

但我收到此错误无法读取未定义的属性“原型(prototype)”,因为我解雇了

var collection = new Collection({collection : MyModel});

在 MyModel 返回之前(我认为)

如果有人有解决方案或帮助我的东西,我将不胜感激:)。

最佳答案

您可以在创建集合后获取集合中每个模型的信息(在 initialize 方法中获取数据实际上是一件坏事,因为该方法不是为此目的而创建的。最好调用显式模型的 fetch 方法(在我们的例子中,我们称之为 fetchLikes))

  var MyModel = Backbone.Model.extend({
fetchLikes: function () {
var UrlGetLike = "https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27https://www.facebook.com/pages/Stackoverflow/1462865420609264%27&format=json";
$.getJSON(UrlGetLike, {
format: "json"
}, _.bind(function (data) {
likes = data[0].like_count;
that.set({
'likes': likes
});
}, this));
}
});

var Collection = Backbone.Collection.extend({
model: MyModel
})

var collection = new Collection();

//.. insert models in the colleciton ..

collection.forEach(function (model) {
model.fetchLikes();
})

请记住,您在 for-loop 中执行 ajax 请求,这被认为是一种不好的做法。仅当您无法在一次请求中获取全部数据时才执行此操作。

关于javascript - 动态改变 Backbone 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704301/

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