2

Learning Spine.js for a new app. The Spine framework is elegant. I am not quite able to get the Ajax persistence working. No error messages, just no activity.

I have a REST api http://localhost:8080/services/api/myservice/persons that returns a JSON list of Person objects, via both the browser and the jQuery.ajax(...) call below in this minimal test.

But calling Person.fetch() yields neither ajaxSuccess nor ajaxFailure, nor trigger a refresh event. Nor does the server register a request. I included "ajax.js" and extended Spine.Model.Ajax. Presumably I'm missing a basic setup, would be grateful for hints.

<script type="text/javascript" src="/appLib/jquery-1.7.js"></script>
<script type="text/javascript" src="/appLib/spine/spine.js"></script>
<script type="text/javascript" src="/appLib/spine/ajax.js"></script>

<script type="text/javascript">
    jQuery(document).ready(function() {

       Spine.Model.host = "http://localhost:8080/services/api/myservice";

        var Person = Spine.Model.sub();
        Person.configure("firstName", "lastName");
        Person.extend("Spine.Model.Ajax");

        // these callbacks are never called
        Person.bind("refresh", function() {alert("refreshed "+Person.count());});  // never called
        Person.bind("ajaxSuccess", function() {alert("ajax success");});           // never called
        Person.bind("ajaxError", function(record, xhr, settings, error) {
            alert("ajaxError"+error);                                              // never called
        });


        Person.fetch(function() {alert("Fetch "+Person.count());});    // 0
        Person.each(function() {alert("Found");});                     // never called


        // but this direct ajax call works fine
        jQuery.getJSON(Spine.Model.host + "/persons", function(result) {           
            for (var i=0, l=result.length; i<l; i++)  {
                var person = Person.init(result[i]);
                person.save();
            }
            alert(Person.count());   // shows correct result
            Person.each(function(p) {alert(p.lastName);});  // shows correct results
        });


    });
</script>
prototype
  • 7,249
  • 15
  • 60
  • 94

1 Answers1

2

Yes, you're extending it with a string - that's never going to work.

Change:

Person.extend("Spine.Model.Ajax");

To:

Person.extend(Spine.Model.Ajax);

Alex MacCaw
  • 984
  • 1
  • 6
  • 19
  • Tremendous thanks!! All works brilliantly. Stunned that I couldn't see that after looking at it so many times. And that I got a reply from the author directly. The OReilly book is very clearly written. – prototype Feb 14 '12 at 01:34