问题
I have a view that is instantiated in an {{#each}} block, so there are multiple instances. Each view needs to have a bound property to an object that is specific to that view instance. So the usual way of declaring a binding:
App.hash = Ember.Object.create({
item1: "one",
item2: "two"
});
App.MyView = Ember.View.extend({
itemBinding: "App.hash.itemN"
});
won't work because When I define what the binding maps to (App.hash.itemN
) I don't know yet whether it should be item1 or item2 (represented in the above code by itemN).
I have found a way around this, that seems a bit kludgey, and am curious if there's a proper way. Here is my solution:
App.MyView = Ember.View.extend({
didInsertElement: function() {
this.set('stub', Ember.Object.create({
itemBinding: "App.hash."+this.get('content')}))
}
})
Then in my template I can do the following:
{{#each App.itemController}}
{{#view App.MyView contentBinding="this"}}
{{stub.item}}
{{/view}}
{{/each}}
Is there a better way to do this? My complaints are that I feel like I'm creating an unnecessary object. Also, if I want other properties of my view to depend on this instance-specific object, I can say .property(stub.item)
which happens to work, despite that when it's declared, stub.item doesn't exist yet.
I thought there might be some way involving manually creating a binding, but I couldn't figure that out.
Thanks!
Update:
I've confirmed that Christopher Swasey's solution works. I've fleshed it out in this Gist:
https://gist.github.com/2606979
This was very helpful, as I learned more about observes and callbacks. Although in the end, I'm not sure how much simpler this solution is. Nonetheless, it works at least as well.
回答1:
You can make stub a computed property:
hashBinding: 'App.hash',
stub: function() {
return this.get('hash').get(this.get('content'))
}.property('hash', 'content').cacheable()
Updated:
contentWillChange: function() {
this.removeObserver('hash.' + this.get('content'), this, 'stubDidChange');
}.observesBefore('content'),
contentDidChange: function() {
this.addObserver('hash.' + this.get('content'), this, 'stubDidChange');
this.stubDidChange();
}.observes('content'),
stubDidChange: function() {
this.notifyPropertyChange('stub');
},
stub: function() {
return this.get('hash').get(this.get('content'))
}.property().cacheable()
来源:https://stackoverflow.com/questions/10406771/what-is-the-ideal-way-to-create-view-instance-specific-bindings-in-emberjs