我最近开始在ASP.NET Web API中使用Ember.js.我很难从服务器加载模型.但现在我拥有它,我想从视图中的商店获取模型.目前我正在开发一个日历应用程序.这是逻辑,
App.IndexRoute = Ember.Route.extend({ //setupController: function (controller) { // // Set the IndexController's `title` // this.controllerFor('application').set('model', App.application.options); //} model: function () { return this.store.findAll('eventList'); }, setupController: function (controller, model) { this.controllerFor('index'); // controller.set('model', App.Events.findAll()); } });
控制器:
App.IndexController = Ember.ArrayController.extend({ sortProperties: ['eventId'], sortAscending: false, //events: Ember.computed.alias('model') });
模型
App.EventList = DS.Model.extend({ eventId: DS.attr('string'), title: DS.attr('string'), start: DS.attr('string'), end: DS.attr('string'), allDay: DS.attr('string') }); App.EventListSerializer = DS.WebAPISerializer.extend({ primaryKey: 'eventId', });
终于看到了
///App.IndexView = Ember.View.extend({ didInsertElement: function () { var events= this.get('controller').get('store'); //the view has been completely inserted into the dom // $('#calendar').fullCalendar(this.get('controller.model')); $('#calendar').fullCalendar({ events: events });
现在我坚持在视图中获取模型.因为一旦didInsertElement
被解雇,我想用我从商店收到的模型初始化日历插件.
var events= this.get('controller').get('store');
不起作用.
但它确实让我这样:
var events = this.get('controller').get('store');
如你所见,我的模型已经存在.那我怎么把它拿出来看?我真的被卡住了,这就是为什么我最后问这个问题.请帮忙...:)
Ember公司有一个默认的setupController
,其中controller.model
是安装程序,所以如果你重写它,你需要做的:
setupController: function (controller, model) { // setup the model controller.set('model', model); // setup other things }
另外,当你使用this.get('controller.model')
像对象返回的数组得到模型时,被调用DS.RecordArray
并且该数组有实例DS.Model
,那个模型不是普通的javascript对象,所以如果你$('#calendar').fullCalendar({ events: events });
期望一个普通的js对象,你需要model.toJSON()
在每个项目中使用记录数组.
这是更新的代码:
App.IndexRoute = Ember.Route.extend({ model: function () { return this.store.findAll('eventList'); }, setupController: function (controller, model) { controller.set('model', model); } }); App.IndexView = Ember.View.extend({ didInsertElement: function () { var events = this.get('controller.model').map(function(record) { return record.toJSON({ includeId: true }); }); $('#calendar').fullCalendar({ events: events }); } });
我希望它有所帮助