Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have set up an ember checkbox:

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

This checkbox is bound to this controller:

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')


});

Essentially it is a checkbox which posts a setting, my problem is setting the original state of the checkbox. When I load the route, I want to have isItChecked() run to set the checkbox's original state.

Example: 1. I go in to settings, click the checkbox 2. I leave the site and come back to the settings page Here is where I want the isItChecked() function to run to query the server and see if the setting is set

If it is set, the get request returns true, I want the checkbox to be checked, hence setting me.isChecked to data (true)

as of right now I can't figure out how to do this, can anyone help me?

I've tried setting it in my App.SettingsRoute's model, but that doesn't seem to be able to run the function in my controller.

Thanks.

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

like image 767
MoDFoX Avatar asked Aug 13 '13 01:08

MoDFoX


1 Answers

One way to accomplish this is by using the route's setupController method.

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);
    })
  }
})

This should get the job done with the fewest changes to your existing code but does have some drawbacks and is not exactly the-ember-way. Probably it would make more sense to have a model object that represents your settings, move ajax code to that model object and use the route's model hook to trigger as needed. See ember-without-ember-data for an example of how that can work.

like image 175
Mike Grassotti Avatar answered Oct 13 '22 01:10

Mike Grassotti