动态改变骨干模型

时间:2014-11-02 20:55:58

标签: javascript backbone.js model requirejs updatemodel

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

所以这里是我的代码:

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;
    }
  });
});

但我得到了这个错误无法读取属性'原型'未定义,因为我解雇了

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

在MyModel返回之前(我认为)

如果有人有解决方案或有什么东西可以帮助我,那将会很感激:)。

1 个答案:

答案 0 :(得分:1)

您可以在创建集合后获取集合中每个模型的信息(在initialize方法中获取数据实际上是一件坏事,因为此方法不是为此目的而创建的。它&#39最好明确地为模型调用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();
  })

请注意,您在ajax中的for-loop次请求被视为不良做法。 只有在无法在一个请求中获取整个数据时才能执行此操作。

相关问题