0

考虑到我是 Backbone 的新手,我已经设法构建了我的第一个 Backbone 应用程序,目前它只根据本地 json 文件列出人员及其国籍:

var Person = Backbone.Model.extend({
    defaults: {
        Name: '',
        Country:''
    }
});

var PersonCollection = Backbone.Collection.extend({
  model: Person,
  url: 'users.json'
});

var PersonList = Backbone.View.extend ({
  el: '.inner',
  initialize: function () {
    var people = new PersonCollection(),
        that = this;
    people.fetch({
      success: function (PersonCollection) {
        var template = _.template($('#people-template').html(), {PersonCollection: PersonCollection.models});
        that.$el.html(template);
      }
    })
  }
});

var GeneratePersonList = new PersonList();

我希望能够编辑/更新单个用户。最好的方法是什么?有一些代码示例会很好。谢谢

4

1 回答 1

0

如果您从平面 json 文件加载它们,您将不会同步对模型的更改。

如果您想避免使用服务器/数据库来保存数据,我的建议是使用Backbone LocalStorage插件,将一些虚拟数据加载到本地存储中,然后从那里使用您的模型。

这是一个非常松散的想法,您将如何做到这一点:

// model ...

// (assuming you've loaded localStorage plugin on your page with underscore and backbone)
var PersonCollection = Backbone.Collection.extend({
  model: Person,
  localStorage: new Backbone.LocalStorage("PersonCollection"), // Unique name within your app.
});

// view ...

// "bootstrap" data in to localStorage, if it is not there already
if (typeof localStorage["PersonCollection"] === 'undefined') { 
   // make ajax request, load your json into local storage 
   $.getJSON('users.json', function (data) {
       localStorage['PersonCollection'] = data;
       init();
   });
} else {
  init();
}

function init () {
  var GeneratePersonList = new PersonList();
}
于 2013-10-11T15:42:46.850 回答