3

What is the 'correct' way to bind from one model to another when the models are stored within an array? Typically I'd imagine that this would be a Controller's content array, but to keep the example simple:

MyApp.websites = [];
MyApp.websites.push(Ember.Object.create({
  name: "Stackoverflow"
}));

MyApp.websites.push(Ember.Object.create({
  name: "Serverfault"
}));

MyApp.favorite = Ember.Object.create({
  // how should this be bound to a specific element of MyApp.websites?
  nameBinding: ?????????
});
2
  • What do you mean by 'specific'? Specific meaning the first item in the array? Commented Dec 14, 2011 at 23:24
  • @pangratz - sure any item in the array would do. I'm primarily interested in whether this is supported by Ember and if so the best approach. Commented Dec 15, 2011 at 3:01

2 Answers 2

6

You can use a property to bind that.

This way:

MyApp.websites = [];
MyApp.websites.push(Ember.Object.create({
  name: "Stackoverflow"
}));

MyApp.websites.push(Ember.Object.create({
  name: "Serverfault"
}));

MyApp.mainController = Ember.Object.create({
  currentWebsiteIndex: 0,
  currentWebsite: function() {
    return MyApp.websites[this.get("currentWebsiteIndex")];
  }.property("currentWebsiteIndex")
});

MyApp.favorite = Ember.Object.create({
  // how should this be bound to a specific element of MyApp.websites?
  nameBinding: "MyApp.mainController.currentWebsite.name"
});

This is just to demonstrate the idea, a better implementation would be:

MyApp.websites = Ember.ArrayProxy.create({
  content: [],
  currentWebsiteIndex: 0,
  currentWebsite: function() {
    return this.objectAt(this.get("currentWebsiteIndex"));
  }.property("currentWebsiteIndex")
});

MyApp.websites.pushObject(Ember.Object.create({
  name: "Stackoverflow"
}));

MyApp.websites.pushObject(Ember.Object.create({
  name: "Serverfault"
}));

MyApp.favorite = Ember.Object.create({
  // how should this be bound to a specific element of MyApp.websites?
  nameBinding: "MyApp.websites.currentWebsite.name"
});
Sign up to request clarification or add additional context in comments.

Comments

2

You probably wouldn't want to use an array to store model objects you're binding to unless you're using {{#each}} in your template.

If you wanted to expand your example a bit further, I could provide more design suggestions.

Also, you'll want to use the observer-aware pushObject() method on Arrays that you're observing/binding to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.