开发者

Code snippet for Backbone.js to save model data.

could anybody post a small code snippet for saving Backbone model to database.

With Backb开发者_C百科one.sync being overridden by jquery.

It would be of great help, Thanks!


From experience, it is better to call AJAX explicitly in the collection and model instead of using the general Sync. Gives you much more flexibility. Here's what we do in Planbox for a collection of tasks in a to-do list.

  TaskCollection = Backbone.Collection.extend({
    // Get all existing tasks from the server
    fetch: function(options) {
      var collection = this;
      // Remove references to callbacks so that calls further down
      // don't trigger them again!
      var onsuccess = options.success; if (options.success) delete options.success;
      var onerror = options.error; if (options.error) delete options.error;
      $.ajax({
        url: '/get_tasks',
        type: 'GET',
        dataType: 'json',
        success: function(object, status) {
          collection.refresh(collection.parse(object));
          if (onsuccess) onsuccess(collection, object);
        },
        error: function(xhr, status, error) {
          if (onerror) onerror(collection, xhr.responseText);
        }
    }
  });

  TaskModel = Backbone.Model.extend({
    // Save a task on the server
    save: function(options) {
      var model = this;
      $.ajax({
        url: '/save_task',
        type: 'POST',
        dataType: 'json',
        data: model.toJSON(),
        success: function(object, status) {
          if (options.success) options.success(model, object);
        },
        error: function(xhr, status, error) {
          if (options.error) options.error(model, object.content);
        }
    }
  });

  var tasks = new TaskCollection();
  tasks.fetch();

Note that we assume the server spits out a unqiue id attribute for each task object. Backbone will use that to identify the model. So you can do something like tasks.get(12) to retrieve task with id 12.

And also note that in Planbox we have a richer set of save functions on models like save_status and move. This gives us the flexibility to add more pre and post processing like validation and update specifics.

And we also extended generic Backbone Collection and Model objects to encapsulate the fetch and save functions above.


myModel = new Model id:'model1'

$.ajax '/urlWhereUWantToSaveModel',
  type: 'POST'
  data: myModel.toJSON()
  dataType: 'json'
  success: (response) ->
    // Server response should be json object with an error property if something went wrong
    if response.error
      console.log 'save failed'
    else
      console.log 'save succeeded'
  error: ->
    console.log 'error'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜