How to generate model id's with Backbone.js

前端 未结 3 645
梦谈多话
梦谈多话 2021-01-30 23:22

I am setting up the backbone sync mechanism and am a bit confused where to generate the id\'s for the models.

When I create a new model, should backbone be generating an

3条回答
  •  青春惊慌失措
    2021-01-30 23:51

    What I understand from your question is that you want to have a collection with models that exist on the server. In order to get these models into the collection you'd have to add call 'fetch()' on the collection.

    The url would be "/users" or something similar, that would have to return an array of objects with user data in there. Each item in the array would then be passed to UserCollection.add(). Well, actually it would be passed all at once, but you get the point.

    After this your collection is populated. The url on the Model is meant for updating and saving the individual model. The url of the collection will also be used for creating models. Backbone's sync is RESTful, like Ruby on Rails. You can actually learn more about it on the documentation of Ruby on Rails:

    http://guides.rubyonrails.org/routing.html

    What you would generally do is have a different url for your model than for your controller. After populating your collection you have id's for each model in there because they came from the server.

    Now when you add a new model based on user input you'd do something like this:

    var HomeModel = Backbone.Model.extend({
        defaults: {
            lead: "not logged in",
        },
    
        url: 'test.php',
    
        initialize: function(){
            _.bindAll(this, 'handleSave', 'handleError');
            // Save already knows if this.isNew.
            this.save(undefined, {success: this.handleSave, error: this.handleError});
        },
    
        handleSave: function(model, response){
            this.model.reset(model);
        },
    
        handleError: function(){
    
        },
    });
    
    var HomeView = Backbone.View.extend({
        initialize: function() {
            _.bindAll(this, 'render');
            this.model = new HomeModel();
            this.model.bind("change", this.render);
        },
    
        el: 'div',
    
        render: function() {    
            // Do things to render...
        }
    });
    
    var homeView = new HomeView();
    

    The example is from someone else's question I answered, I just add the relevant things.

    The general idea is to save the model when it is created, if you need it somewhere else you can just move the code into a function of the model and call that based on events or anything else.

提交回复
热议问题