Josh Rickard
Josh Rickard

Reputation: 1603

Ember.js binding models stored within an array

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

Upvotes: 3

Views: 3233

Answers (2)

Wilker Lucio
Wilker Lucio

Reputation: 2749

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

Upvotes: 6

ebryn
ebryn

Reputation: 4397

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.

Upvotes: 2

Related Questions