2014-11-02 107 views
0

在這裏我的問題,我想動態地改變我的模型(當集合被實例化時,動態地改變我模型中的變量)。動態改變骨幹模型

所以在這裏我的代碼:

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是返回(我認爲)

如果任何人有解決方案或東西來幫助我,它將不勝感激:)。

+0

那麼,你是否解決了你的問題? – Mironor 2014-11-03 06:42:24

回答

1

您可以在創建後爲集合中的每個模型獲取信息(在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-loopajax請求。 只有當您無法在一個請求中獲取整個數據時才執行此操作。