考虑到我是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();
我希望能够编辑/更新单个用户。这样做的最佳方式是什么?有一些代码示例会很高兴。谢谢
答案 0 :(得分:0)
如果要从平面json文件加载更改,则不会将更改同步到模型。
如果你想避免使用server / db来保存你的数据,我的建议是使用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();
}