开发者

Trying to populate backbone collections on page load

Backbone (and pretty much .js for that matter) newbie. Trying to learn MVC architecture in the client.

The goal is to recreate this jQuery functionality

$.getJSON('/application/listsurveys', function(data) {

        $.each(data.surveys,function(i,item) {
           $('#surveyListTable').append( '<tr onMouseover="onMouseOverHandler()" onMouseout="onMouseOutHandler()" >'
                            + '<td id="testData">'+ item.title + '<br>ID ' + item.surveyId + '</td>'
                            + '<td>' + new Date( item.uploadDate ).toLocaleDateString() + '</td>'
                            + '<td>' + item.ndgUser.username + '</td>'
                            + '<td><开发者_StackOverflow中文版;a href="">' + item.resultCollection.length + '</a></td>'
                            + '<td width=250><img src="images/back.jpg" id=Tools></td>'
                            + '</tr>' );
                                             });
             });

but i cannot get past the JSON loading - what i have so far is this

var Survey = Backbone.Model.extend({
    initialize: function(){
            console.log("A single survey model was created");
                          }
    });

var SurveyList = Backbone.Collection.extend({
    initialize: function(){             
             console.log("A survey collection was created");
                          },
    url :'/application/listsurveys',
    model: Survey
});


var App = {
     init: function() { 
             var surveys  = new SurveyList({}); 
             surveys.fetch({success: loadApp});      
       }
};

// kick off the application
$(document).ready(function() {
     App.init();
 });

which gives a cannot call ajax method of undefined error in Backbone. I read that

Fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place.

so I tried hard coding the JSON at model creation like

var App = {
 init: function() { 
         var survey = new Survey({"surveys":[{"available":1,"id":1,"ndgUser":{"username":"admin"},"resultCollection":[],"surveyId":"1263929563","title":"Demo Survey","uploadDate":1311603000000}]});
         var surveyObject = survey.get('surveys');
         available = surveyObject[0].available;
         alert(available);     
   }

};

and this alerts the expected result of 1. How can i move on from here and pull this JSON when the page loads?


Your hint is here: cannot call ajax of undefined

Backbone does not supply an ajax method. It relies on a library for that, using either jQuery or Zepto (both of which have the same API for Ajax calls). You have to include jQuery in your script.

Backbone is just a library for managing complex data relations, a sort-of organization tool-- a very powerful one, but that's all it is. It is not a substitute for a DOM manipulation tool such as jQuery. If you were using Backbone on the server, with Node.js for example, you would have to override the sync method for your models and collections to use something other than Ajax-- presumably, you'd be saving to a database of some kind.


Just in case others are having this problem and come across this post it seems that the order the libraries are imported is important. JQuery first, then underscore and then backbone. Something like

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script>window.jQuery || document.write('<script src="javascripts/libs/jquery-1.6.2.min.js"><\/script>')</script>

  <!-- Grab utility-belt library underscore.js, with a protocol relative URL; fall back to local if offline -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.7/underscore-min.js"></script>
  <script>window.jQuery || document.write('<script src="javascripts/libs/underscore-1.1.7.min.js"><\/script>')</script>

  <!-- Grab backbone.js (Google, we host the other stuff OK), with a protocol relative URL; fall back to local if offline-->
  <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
  <script>window.jQuery || document.write('<script src="javascripts/libs/backbone-0.5.3.min.js"><\/script>')</script> 


Make sure you have jQuery or Zepto loaded - Backbone.sync() method eventually calls $.ajax() which is where you get your error, which just means $ is undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜