EmberJS 模型JSON约定
描述
REST适配器使用从服务器请求的记录的JSON表示。
格式
{ "person": { "firstName": "Starc", "lastName": "Mack" } }
例子
<!DOCTYPE html> <html> <head> <title>Emberjs JSON Conventions</title> <!-- CDN's --> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <!--Mockjax CDN--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <script type="text/x-handlebars"> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="index"> <h2>Authors Info: </h2> {{#each author in controller}} <section> <h3>{{author.name}}</h3> <ul> <li><b>Hobby:</b> {{author.authorAttributes.hobby}}</li> <li> <b>Book: </b> {{author.authorAttributes.books}} </li> </ul> </section> {{/each}} </script> <script type="text/javascript"> App = Ember.Application.create(); App.IndexRoute = Ember.Route.extend({ model: function() { return this.get('store').find('author'); } }); App.ApplicationAdapter= DS.ActiveModelAdapter; App.Author = DS.Model.extend({ //data model name: DS.attr('string'), authorAttributes: DS.attr() }); App.Book = DS.Model.extend({ //data model title: DS.attr('string'), //belongsTo relationships in the JSON representation should be the camelized version of the Ember Data author: DS.belongsTo('author') }); //static JSON format for emberjs $.mockjax({ type: 'GET', url: '/authors', status: '200', dataType: 'json', responseText: { authors:[{ id: 1, name: "Herbert Schildt", authorAttributes: { hobby: "Writing", books: "C++" } },{ id: 2, name: "Balaguruswamy", //Sideloaded Relationships authorAttributes: { hobby: "Writing", books: "Java" } }] } }); </script> </body> </html>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上面的代码保存在models_json.html文件中
在浏览器中打开此HTML文件。