Can I add an additional computed property to an Em

2019-07-29 22:05发布

问题:

I'm working on a legacy Ember app that has a bit of a funky setup and I'm trying to clean things up and follow conventions a bit more. One issue is that, rather than returning an array from the model hook of an index route, we're returning an object that contains an array. So, I'm wrapping the model in an ArrayProxy in setupController like this:

setupController: (controller, model) ->
  model_proxy = Ember.ArrayProxy.create({content: model.get('item')})
  controller.set('content', model_proxy)

This actually works (i.e. content is updated when the AJAX promise resolves and model.item is loaded with data). The problem is, there's another property on model that I also need in my controller. model has a needsLoader property which is initialized to true and then set to false when the promise resolves. We're using this to show a spinner to the user while the data is being fetched from the server.

So, my question is: is there any way that I can proxy needsLoader in the ArrayProxy?

One solution I have tried is to hook the original model onto the controller in a non-standard way:

setupController: (controller, model) ->
  ....
  controller.set('_model', model)
  ....

This lets me access needsLoader from the controller by calling @get('_model.needsLoader'). It works, but I'd like to do all of the dirty work in the Router so that I have a clean interface in my controller to just call model as usual.

Thanks!

回答1:

Not sure if it makes sense, but you can create your own type:

var myArrayProxy = Ember.ArrayProxy.extend({
  countPlusTen: function(){
    return this.get('content.length') + 10;
  }.property('content.length')
});


var instance = myArrayProxy.create({
  content: [1,2,3]
});

console.log(instance.get('countPlusTen'));

Example: http://emberjs.jsbin.com/novavuqi/1/edit