Access EmberJS Data from a Component

February 11th, 2015

emberjs

 

I am building a small EmberJS application using the Ember-CLI. In the application I have a map that I wanted to load some data to. I ended up picking an Ember Component to control the map so that I could use the didInsertElement method to make sure that my maps markup was ready to be initialized.

//Component called main-map
export default Ember.Component.extend({
	componentMap: '',
	didInsertElement: function() {
		navigator.geolocation.getCurrentPosition(position => {
			//Initialize the map
			this.populateMap();
		});
	},
        populateMap() {
            ...
        }
});

After I had my map on the page I wanted to access the data store from my parent controller. After googling around for a while I did not come up with exactly what I wanted. By default the data from an Ember Controller or Route is not injected into a Component. After asking on Stackoverflow, the answer was pretty simple!

I use my main-map component in a template like such:

//index.hbs template
{{main-map}}

From there you can actually add attributes to a component, and it is here that we add our data! The process is pretty simple, lets look at the new component in the template.

{{main-map data=model}}

It is that simple, you might be asking your self, where does this model come from though? This was defined inside my ApplicationRoute.

export default Ember.Route.extend({
	model: function() {
		return this.store.find('restaurant');
	}
});

In this route I return my store as the model for the route, that way I can use it through out!

With this I was able to simply get my data and iterate over them however I wished! So the populateMap method in my component now looks like this.

populateMap: function() {
	//Get store
	var store = this.get('data');
	//Search Store
	store.map(item => {
		console.log(item.get('name'));
	});
}

Done and done.


Warning: count(): Parameter must be an array or an object that implements Countable in /home/ryanch6/public_html/wp-includes/class-wp-comment-query.php on line 405