EmberJS 路由器异步加载模型
2018-01-04 11:34 更新
描述
它在渲染模板之前从模型钩子返回一个promise,而getJSON()方法返回一个JSON的promise。 Ember.Js使用promise对象来帮助连续地渲染数据。
语句
Ember.Route.extend({ model: function() { return Ember.$.getJSON('filename'); } });
例子
<!DOCTYPE html> <html> <head> <title>Emberjs Asynchronously Loading Models</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> <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"> <!-- loop over the JSON data --> <h1>JSON file of the specified url:</h1> {{#each pr in model}} <p><b>Created at</b>: {{pr.created_at}}</p> <p><b>Title</b>: {{pr.title}}</p> {{/each}} </script> <script type="text/javascript"> App = Ember.Application.create(); App.IndexRoute = Ember.Route.extend({ model: function() { var url = 'https://api.github.com/repos/emberjs/ember.js/pulls'; //get the JSON values from the specified url return Ember.$.getJSON(url).then(function(data) { //adds the data to/from an array. splice(0,2) is the number of items to be displayed: is 2 return data.splice(0, 2); }); } }); </script> </body> </html>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上面的代码保存在routing_async_mod.html文件中
在浏览器中打开此HTML文件。
以上内容是否对您有帮助:
更多建议: