简体   繁体   中英

spine.js populate model instances at start up

Absolute beginner here. I want to load data into models as soon as the page loads. Before anything else is executed. At the moment I have this code.

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

So when the page has finished loading the controller init function is called, which retrieves the json data and passes it to the Model which parses it and creates the individual instances.

Am I doing this wrong? I have seen Fetch function in the documentation but with no example of how it works.

You might want to use Spine's framework to do this:

  1. Instead of firing your own jQuery.getJSON(), include Spine.Ajax in your Model.
     Portfolio.extend(Spine.Model.Ajax);  
  2. Set the Spine.Model.host to your server
  3. Add url attribute/method to your Portfolio object to something like 'xml/data.json'
  4. Call Portfolio.fetch()
  5. Override Portfolio.fetch() function to extract just the node of array data or whatever initialization you had in mind just like the configure. If I am not mistaken, fetch() will load the objects and set all the attributes provided in the JSON even if they are not configured in Model @configure call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM