0

这里绝对是初学者。我想在页面加载后立即将数据加载到模型中。在执行任何其他操作之前。目前我有这个代码。

// Model code
var Portfolio = Spine.Model.sub({});
Portfolio.configure("Portfolio")

Portfolio.extend({
  populate: function(values){
    for(var i in values[0]){
     // add attributes to Model
      this.attributes.push(i);
    }
    for(var j = 0; j < values.length; j++ ){
      var tmpInst =  this.create(values[j]);
      tmpInst.save();
    }
  }
});

// app controller code
$(function(){
   var App =Spine.Controller.sub({
    init: function(){
      jQuery.getJSON("../xml/data.json", 
        function(result){ 
             Portfolio.populate(result['content']);
        }
      ).complete(function(result) { 
          // do other stuff
      });
    }
  })
    var app = new App();
});

因此,当页面完成加载时,将init调用控制器函数,该函数检索 json 数据并将其传递给模型,模型对其进行解析并创建各个实例。

我做错了吗?我在文档中看到了 Fetch 函数,但没有关于它是如何工作的示例。

4

1 回答 1

0

您可能想使用 Spine 的框架来执行此操作:

  1. 不要触发你自己的 jQuery.getJSON(),而是在你的模型中包含 Spine.Ajax。
    Portfolio.extend(Spine.Model.Ajax);
  2. 将 Spine.Model.host 设置为您的服务器
  3. 将 url 属性/方法添加到您的 Portfolio 对象,例如“xml/data.json”
  4. 调用 Portfolio.fetch()
  5. 覆盖 Portfolio.fetch() 函数以仅提取数组数据的节点或您想到的任何初始化,就像配置一样。如果我没记错的话, fetch() 将加载对象并设置 JSON 中提供的所有属性,即使它们没有在 Model @configure 调用中配置
于 2012-10-19T20:09:24.117 回答