1
votes

I am working on a small bill sharing app.

I have a Bill model that hasMany('people') for who's responsible. A User model that hasMany('bills'). And a BillGroup model that contains a hasMany relationship for the two previous models.

I want to create a form for editing a bill. I use a #each loop for both the items in the BillGroup. I have a bill and a person, and I want the box to be checked if the person exists in the bill. I have created a JsBin to illustrate my problem.

http://emberjs.jsbin.com/sesiyozi/20/edit

Thanks.

1

1 Answers

1
votes

You present a fairly tricky problem due to the fact that your model doesn't match your desired template. This is especially true since handlebars doesn't support conditional ifs etc.

One route is to mangle the model to match what you want your template to look like.

return this.store.find('billGroup',1).then(function(record){
  var usersPromise = record.get('users'),
    billsPromise = record.get('bills');

  return Em.RSVP.hash({
    users: usersPromise,
    bills: billsPromise
  });
}).then(function(model){
  var responsibles = Em.RSVP.all(model.bills.getEach('responsibles'));
  return responsibles.then(function(){
    return model;
  });
}).then(function(model){
  var ret = [];
  model.bills.forEach(function(bill){
    var item = [];
    model.users.forEach(function(user){
      var ub = App.UserBill.create({user:user, bill: bill});
      item.push(ub);
    });
    ret.push(item);
  });
  return ret;
});

http://emberjs.jsbin.com/qojun/3/edit

That is fairly painful in my opinion, and hardly asynchronous friendly. I think it'd be easier to set up a custom view that's aware of the user/bill in that scope.

View

App.FooView = Em.View.extend({
  isResponsible: function(object){
    var responsibles = this.get('bill.responsible');
    if(responsibles){
      console.log(responsibles.indexOf(this.get('user')));
      return responsibles.indexOf(this.get('user')) >=0;
    }
    return false;
  }.property('[email protected]', 'user.id') //just here for debugging
});

Template

{{#view App.FooView bill=bill user=user}}
   {{input type="checkbox" name="responsible" checked=view.isResponsible}}
   {{user.name}}
{{/view}}

http://emberjs.jsbin.com/sesiyozi/21/edit