2013-10-08 49 views
1

目前,我尝试将我的ember.js应用程序连接到我的网络服务器。该Web应用程序有一个日期选择器。选定日期后,我喜欢我的模型“重新加载”。随着重新加载,我的意思是问我的网络服务器包含特定日期的新数据。在前台事件发生后从服务器加载数据

下面你看到我的路线与服务器联系以获取所需信息。

App.PicturesRoute = Ember.Route.extend({ 
    model: function(params) { 
     return $.getJSON('http://api.<server>.com/pictures?date=' + params.date).then(function(data) { 
      return data.pictures.map(function(picture) { 
       picture.body = picture.content; 
       return event; 
      }); 
     }); 
    } 
}); 

如果我手动在字符串中写入日期,那么一切正常,我会收到数据。现在,我有问题,我不知道如何动态地做到这一点。我应该如何创建UI和模型之间的最佳连接。当然,我可以在我的控制器中实现一个动作,但该控制器应该如何调用/重新加载模型?

回答

0

由于date是您网址的一部分,因此您应该只使用transitionTotransitionToRoute。您可能设置了一条路线,可让您匹配类似/pictures/2013-10-09的网址。事情变得有点时髦,因为2013-10-09不是一个真正的对象ID。通常情况下transitionToRoute Ember希望你能通过一个实时模型来代表你正在转换的内容。如果直接命中路线(没有link-totransitionTo),这将是Ember执行model挂钩时将查找的相同对象。由于日期确实是一个查询参数,而不是一个id,所以您可以使用setupController方法来避开funkiness。

所以,你的路线可能是这个样子(这是简化的,你当然要使用适当的AJAX调用):

App.PicturesRoute = Ember.Route.extend({ 
    model : function(params){ 
    console.log('calling model for PicturesRoute'); 
    return { date : params.date }; // return a fake model 
    }, 
    setupController : function(controller, model){ 
    // Make sure not to call super since we don't want to set 
    // a single object instead of an array 
    // this._super(controller,model); <-- do not use! 
    console.log('calling setupController for PicturesRoute'); 
    // Instead set the `date` property directly 
    controller.set('date',model.date); 
    // Then find/build an array and set it as the model 
    var pictures = [ 
     {name : "Pic 1 - " + model.date}, 
     {name : "Pic 2 - " + model.date} 
    ]; 
    controller.set('model',pictures); 
    console.log(model); 
    } 
}); 

然后在应用程序中,当你发现从变化在日期选择器,你会打电话来是这样的:

var dateFromPicker = ... // however you get a hold of the date string from the picker 
var fakeModel = { date : dateFromPicker }; 
this.transitionTo('pictures',fakeModel); 

这里有一个JSBin显示这个想法的一个非常简化的版本:http://jsbin.com/ucanam/1396/edit

我希望是有道理的。

相关问题