问题 路由加载时运行ember控制器函数以设置控制复选框的属性


我已经设置了一个ember复选框:

{{view Ember.Checkbox checkedBinding='isChecked'}}

此复选框绑定到此控制器:

App.SettingsController = Ember.Controller.extend({

isChecked: false,
isItChecked: function(){

    var me = this;
    $.getJSON('ajax/checkIfUseLowRes.php', function(data){
        //console.log(data);
        //me.isChecked = data;
        me.set('isChecked', data);
        //console.log(me.isChecked);

    })

},
sendSetting: function(){

    var isChecked = this.isChecked;
    //this.set('isChecked', !isChecked);
    console.log(isChecked);

    $.post('ajax/setLowRes.php', {useLowRes: isChecked});
    App.nameSpace.set('needsRefresh', true);

}.observes('isChecked')


});

基本上它是一个发布设置的复选框,我的问题是设置复选框的原始状态。当我加载路线时,我想拥有 isItChecked() 运行以设置复选框的原始状态。

例: 1.我进入设置,单击复选框 2.我离开了网站并返回设置页面 这是我想要的地方 isItChecked() 运行以查询服务器并查看是否已设置的功能

如果设置,get请求返回true,我想要选中复选框,因此将me.isChecked设置为data(true)

截至目前我无法弄清楚如何做到这一点,任何人都可以帮助我吗?

我试过把它设置在我的 App.SettingsRoute的模型,但似乎无法在我的控制器中运行该功能。

谢谢。

JSBin:http://jsbin.com/ukuwiq/1/edit


10843
2017-08-13 01:14


起源



答案:


实现此目的的一种方法是使用route的setupController方法。

App.SettingsRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    $.getJSON('ajax/checkIfUseLowRes.php', function(data){
      console.log('setting isChecked to: ', data);
      controller.set('isChecked', data);
    })
  }
})

这应该通过对现有代码进行最少的更改来完成工作,但确实存在一些缺点,并不完全正确 在-余烬路。可能有一个代表你的设置的模型对象,将ajax代码移动到该模型对象并使用路径的模型钩子根据需要触发更有意义。看到 烬,而无需-余烬数据 有关如何工作的一个例子。


8
2017-08-13 01:41



谢谢!这帮了很多忙。 - MoDFoX


答案:


实现此目的的一种方法是使用route的setupController方法。

App.SettingsRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    $.getJSON('ajax/checkIfUseLowRes.php', function(data){
      console.log('setting isChecked to: ', data);
      controller.set('isChecked', data);
    })
  }
})

这应该通过对现有代码进行最少的更改来完成工作,但确实存在一些缺点,并不完全正确 在-余烬路。可能有一个代表你的设置的模型对象,将ajax代码移动到该模型对象并使用路径的模型钩子根据需要触发更有意义。看到 烬,而无需-余烬数据 有关如何工作的一个例子。


8
2017-08-13 01:41



谢谢!这帮了很多忙。 - MoDFoX


正如迈克所说,你可以使用'setupController',或者你也可以使用它:

App.SettingsRoute = Ember.Route.extend({
  activate: function() {
    this.controllerFor('settings').isItChecked();
  }
})

6
2017-08-13 03:24



它不应该是 this.controllerFor('settings').send('isItChecked');? - intuitivepixel


你能不能只使用init函数?例如

App.IndexController = Ember.ObjectController.extend({
    init: function() {
    console.log("function run");
},

0
2017-12-23 16:05



这只会执行一次,而不是每次都显示控制器。 - bouke