简体   繁体   中英

Communicating with server with Backbone.js

I'm a newbie web developer diving into Backbone for the first time. One major question I've been grappling with (actually spending a lot of the last 2 days researching to no avail) is how exactly Backbone communicates with the server.

In my previous projects, I've been able to fetch data from my database using PHP and jQuery's $.getJSON method. I'm also able to do this when I use Backbone (ex. myCollection.url = "todos.php" ). However, in every single tutorial, documentation, example code I've looked at, the url for the collection is always set as a directory and the urlRoot is directory/id (ex. myCollection.url = "/todos" and myModel.urlRoot = "/todos/5" .

My question is how exactly is this managed? It seems a lot cleaner than the traditional way I was doing by adding GET parameters to my calls. At first I thought this was routing, but that seems to be only related to setting browser history and stuff. Some of the source code I've looked at uses SLIM PHP and Rails (neither of which I've used) but I have no clue how any of the parts fit together.

Backbone has its own api for communicating with server, such as fetch, save, destory.In fact, these methods do the same things with jQuery's $.ajax. For example, you use backbone's fetch in this way:

var UserModel = Backbone.Model.extend({     
    url : "rootURL/user",
});
var user = new UserModel;
user.fetch(
    data:{
        userId : 1,          //the webservice will be: rootURL/user?userId=1  GET;
    }
    success:function(model, response, options){
        //callback
    },
    error:function(model, response, options){
        //callback
    },
);

But you can also use the same way as in the jQuery to communicate with server in backbone's application.For example:

var UserView = Backbone.View.extend({
    render: function(){
        //do something
    }
    getUser: function(userId){     
        $.get("rootURL/user", 
             { userId : userId},
             success:function(data){
                 //callback
             }
          );
    }
});

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