1

I wanted to see how i could save a model to server using model.save() method when urlRoot is specified on the extended model, but ajax request never fires when i ask for model.fetch() or do model.save(). note: Is hope this is possible without using Collection i suppose?.

HTML

<div id="placeholder"></div>
<script type="text/template" id="view_template">
    Hello <%= name %>, here is your script <%= script %>
</script>

Model

 window["model"] = Backbone.Model.extend({
        initialize: function () {
            console.log("CREATED");
        },
        defaults:{
            name:"Please enter your name",
            script:"Hello World"
        },
        urlRoot: "index.aspx",
        validate: function (attrs) {

        },
        sync: function (method, model, success, error) {
            console.log("SYNCING", arguments);
        }
    });

View

 window["view"] = Backbone.View.extend({
        template:_.template($("#view_template").html()),
        initialize: function () {
            console.log("INITIALISED VIEW");
            this.model.bind("change","render",this);
        },
        render: function (model) {
                console.log("RENDERING");
                $(this.el).append(this.template(model));
                return this;
        }
    });

Application

$("document").ready(function () {

    var myModel = new model({
        name: "Stack Overflow",
        script: "alert('Hi SO')"
    });

    var myView = new view({
        model: myModel,
        el: $("#placeholder")

    });

    console.log("SAVING");
    myModel.save();        
    console.log("FETCHING");
    myModel.fetch();


});

as you can see in application i call save & fetch but as per documentation this should fire ajax request with POST -> SAVE & GET -> FETCH. But all it does is log's arguments into console in the sync function.

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178

1 Answers1

1

I think the only reason you are not seeing any Ajax requests is that you have overridden the Model.sync method. Normally you would only do this if you wanted to replace the default Ajax syncing implemented in Backbone.sync. See the following line in Model.fetch in backbone.js:

return (this.sync || Backbone.sync).call(this, 'read', this, options);

I did a quick test with your code and I am seeing the Ajax requests if I rename your Model.sync method.

Steve
  • 15,606
  • 3
  • 44
  • 39
  • awesome :) i found it out after reading the docs correctly. btw could you look into this question too http://stackoverflow.com/questions/7670709/invalid-web-service-call-missing-value-for-parameter-with-backbone-and-webservic – Deeptechtons Oct 06 '11 at 08:38
  • Looking at the other question I can now see why you might need to override sync. I haven't ever had to wire ASP.NET Web Services with backbone.js. – Steve Oct 06 '11 at 10:46