开发者

What component of backbone.js should communicate with the server?

开发者 https://www.devze.com 2023-03-17 19:19 出处:网络
I want to do a basic CRUD app with backbone.js. So I want to list some stuff from the server, create and edit them.

I want to do a basic CRUD app with backbone.js. So I want to list some stuff from the server, create and edit them.

This is how I understand this:

Both my Model and Collection contain a url. The collection will fetch the data and the model will create/save() the data.

The View handles all the interaction, such as calling the collection.fetch or model.save then adding the model to the collection after a success.

The url property on both model and collection seems like duplicate code to me. Is this the correct way to do server interaction?

This is how I do my structure for reference:

window.User = Backbone.Model.extend({
    initialize: function () {
    },
    defaults:
       {
           Name: '开发者_Go百科',
           Age: 0,
           Items: []
       }
});

window.UserList = Backbone.Collection.extend({
    model: User,
    url: "/Users"
});


window.UserView = Backbone.View.extend({
    el: 'body',
    collection: new window.UserList,
    template: _.template($('#user-view-template').html()),
    events: { "submit form#newUser": "addItem" },
    initialize: function () {
        _.bindAll(this, 'render', 'update', 'addItem');
        this.collection.bind('refresh', this.render);
        this.collection.bind('change', this.render);
        this.update();
    },
    render: function () {
        $("#sup").html(this.template({ users: this.collection.toJSON() }));
        return this;
    },
    update: function () {
        this.collection.fetch();
    },
    addItem: function (e) {
        e.preventDefault();
        var person_attrs = $(e.target).serializeObject();
        this.collection.create(person_attrs, {
            success: function (saved_person, data) {
                if (data.Result == "Success") {
                    alert("success");
                }
                else {
                    alert(data.Message);
                }
            },
            error: function (aborted_person, response) {
                alert("Server Error");
            }
        });
        return false;
    }
});

window.View = new window.UserView;


There is a url on both Model and Collection for the sake of flexibility.

By default the Model will build its url based on the url defined in the collection and its id, but you can override this functionality if you need alternative behaviour or if your model exists outside of a collection.

Backbone is very much in tune with RESTful apis. An example resource in a RESTful api could be:

Dog

where

  • GET -> /dog returns a list of dogs
  • POST -> /dog creates a new dog
  • GET -> /dog/1 returns the dog with id of 1
  • PUT -> /dog/1 updates the dog with id of 1 with new data

The corresponding in Backbone could be

  • DogCollection.url = "/dog"
  • DogModel.url = collectionUrl+this.id?

So if you have a new model object fido = new DogModel({name:'fido'}) how do you save it?

you have 2 options:

  1. Ensure DogModel.url() is over written appropriately, and then feel free to call dog.save()
  2. Attach the model to a collection. So for example, if you already have a collection dogsCollection you can use its create method. Either: dogsCollection.create(fido) or dogsCollection.create({name:'Fido'}) or dogsCollection.create(new DogModel({name:'Fido'}) - as you please


You don't need the url property on the model. Just on the collection. If you have a url on the collection as

/foo

and a model with an

id = 76

then as long as the model is part of the collection it can figure out it's own restful url as

/foo/76

You only ever have to call model.save. There is no need to "communicate" directly with the server. Backbone.js takes care of handling the choice of HTTP verb to use

0

精彩评论

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

关注公众号