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

Running an ember controller function when route loads to set property that controls a checkbox

本文关键字:控制 设置 复选框 属性 函数 加载 运行 成员 控制器 路由      更新时间:2023-09-26

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

{{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

实现这一点的一种方法是使用路由的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代码移动到该模型对象,并根据需要使用路由的模型挂钩进行触发会更有意义。有关如何工作的示例,请参阅没有ember数据的ember。

正如Mike所说,您可以使用"setupController",也可以使用以下内容:

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

您不能只使用init函数吗?例如

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