2013-10-11 109 views
0

考虑到我是新来的骨干我已成功地建立基于本地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

如果您从平面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(); 
} 
+0

在init()不会被调用。我已经把一个console.log('这里'),我可以看到,在控制台,但初始化()不起作用.. – Alex

+0

@Alex你的控制台告诉你关于ajax请求的任何其他内容吗?我假设它或者是您提供文件的方式的一个路径或问题。你使用网络服务器吗? –

+0

这是我迄今为止:http://jsfiddle.net/rUdTs/我只使用mamp来查看文件,因为最终我会使用一些php,并且想要在本地进行测试.. – Alex