emberjs ArrayController doesn't work in template - ember.js

I am trying out ember.js and I am struggling with rendering an array of items to the template:
index.html
<script type="text/x-handlebars">
{{App.test}}
</script>
<script type="text/x-handlebars">
{{#each App.eventsController}}
<p>{{title}}</p>
{{/each}}
</script>
<!-- le javascript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>
<script src="js/libs/handlebars-1.0.0.beta.6.js"></script>
<script src="js/libs/ember-1.0.pre.min.js"></script>
<script src="js/app.js"></script>
</body>
app.js
var App = Em.Application.create({
test : 'does it work?...'
});
App.Event = Ember.Object.extend({
title: '',
body: ''
});
App.eventsController = Ember.ArrayController.create({
events: [],
init: function() {
self = this;
self.pushObject(App.Event.create({
title: "Event 1",
body: "Content"
}));
}
});
The first binding (App.test) does work fine. Only my second call does nothing but putting an empty handlebar-script-tag into my DOM.
So what am I missing here?

If you override init you need to make sure to call this._super so the controller can finish its setup process. Once you do this your code should be working as expected.
init: function() {
this._super();
this.get('content').pushObject(App.Event.create({
title: "Event 1",
body: "Content"
}));
}
I've created a jsfiddle for you so you can see it working: http://jsfiddle.net/qKXJt/188/

You'd want to put your eventsController's data inside the 'content' property:
App.eventsController = Ember.ArrayController.create({
content: [],
init: function() {
this.get('content').pushObject(App.Event.create({
title: "Event 1",
body: "Content"
}));
}
});
Your template {{#each App.eventsController}} should automatically pick up the changes and display your title.

Related

Why is itemController not set in the child view?

I want App.IndexRowController to be the controller for the three row views. Instead Ember sets them to plain Objects. I believe I'm properly setting itemController in the DataIndexController. I a version of this code without the nested route working as expected. Do I need to do something special when working with nested routes/needs?
JSBin: http://jsbin.com/sazafi/edit?html,css,js,output
To see the behavior go to #/data/index. Notice there are three li elements but no corresponding text (from getName). The getName controller property isn't accessible from the row template. Ember docs say that setting the itemController in the ArrayController should make that controller available to the template specified in itemViewClass. Take a look at the Ember Inspector and see that the controller for the three views is an Ember.Object, not App.IndexRowController.
JavaScript:
App = Ember.Application.create();
App.Router.map(function() {
this.resource("data", function() {
this.route("index")
});
});
App.DataIndexRoute = Ember.Route.extend({
model: function() {
return(
[
Ember.Object.create({name: 'row 1'}),
Ember.Object.create({name: 'row 2'}),
Ember.Object.create({name: 'row 3'})
]);
}
});
App.DataController = Ember.ArrayController.extend({
filter: ''
});
App.DataIndexController = Ember.ArrayController.extend({
needs: ['data'],
itemController: 'indexRow',
filter: Ember.computed.alias("controllers.data.filter"),
filteredContent: function(){
var filter = this.get('filter');
var list = this.get('arrangedContent');
return list.filter(function(item) {
return item.get('name').match(filter);
});
}.property('content', 'filter')
});
App.IndexRowController = Ember.ObjectController.extend({
// This method isn't accessible from the row template
getName: function() {
return(this.get('content').get('name'));
}.property()
});
App.DataIndexView = Ember.CollectionView.extend({
tagName: 'ul',
content: function(){
return this.get('controller.filteredContent')
}.property('controller.filteredContent'),
itemViewClass: Ember.View.extend({
controllerBinding: 'content',
templateName: 'row'
})
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Collection View</title>
<script src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.1.2.js"> </script>
<script src="http://builds.emberjs.com/release/ember.js"></script>
<script src="app.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="application">
<h1>CollectionView With Item View</h1>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="data">
{{input type="text" placeholder='row 1' value=filter}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="row">
{{getName}}
</script>
</body>
</html>
EDIT: I have a working example of how to set the controller in a child view of a Ember.ContainerView and how to filter the contents here: https://github.com/mkolenda/ember-listview-with-filtering. ListView is a descendent of ContainerView.
Simple solution is to use an {{each}} instead of a CollectionView.
This is a well-known "feature", aka design bug, in the Ember design for array controllers, item controllers, and collection views. It shouldn't be too hard to find references on the web about the problem and some suggested hacks/workarounds. You might start with https://github.com/emberjs/ember.js/issues/4137 or https://github.com/emberjs/ember.js/issues/5267.

How to set Default Value in Ember js

Using Below code i have created Ember View.
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div>
{{view "select" content=model prompt="Please select a name" selectionBinding="controllers.comboBox.model" optionValuePath="content.title" optionLabelPath="content.body" }}
</div>
<div>
{{view "select" content=model1 prompt="Please select a name" optionValuePath="content.title" optionLabelPath="content.title" }}
</div>
</script>
and App.Js
App = Ember.Application.create({
});
App.Router.map(function () {
});
App.IndexRoute = Ember.Route.extend({
model: function () {
return posts;
}
});
App.IndexController = Em.ArrayController.extend({
needs: ["comboBox"],
sendValueToServer: function () {
document.getElementById("comboval").value = this.get("controllers.comboBox.model.title");
}.observes("controllers.comboBox.model"),
model1: function () {
var valueq = this.get('controllers.comboBox.model.title');
console.log("value "+valueq);
return posts1;
}.property("controllers.comboBox.model")
});
App.ComboBoxController = Em.Controller.extend({
model: null,
});
App.ComboBox1Controller = Em.Controller.extend({
model1: null,
});
posts = [{
title: "Raja",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
},
{
title: "Broken",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}
];
posts1 = [{
title: "Raja",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
},
{
title: "Broken",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}
];
Above code using Prompt I was showing "Please select a name" Default Value.
but Initially i dont want Please select a name default value.
my requirement is need to show second value as a default value.
how can i do this.
In association to the question mentioned here,
Second dropdown not calling EveryTime Based on First drop down
To set a default value all it is required is to set a value to the bound property of the specific drop down.
http://emberjs.jsbin.com/loqivasova/1/edit
js
App.ComboBoxController = Em.Controller.extend({
model: posts[0],
});
if however it is required to also modify the second drop down based on this default value, then just add on("init") to the setComboBox1Model1 function,
js
setComboBox1Model1:function(){
var valueq = this.get('controllers.comboBox.model.title');
var valueFromPosts1 = posts1.findBy("title",valueq);
this.set("controllers.comboBox1.model1",valueFromPosts1?valueFromPosts1:null);
}.observes("controllers.comboBox.model").on("init")
http://emberjs.jsbin.com/jogaqinugi/1/edit?html,js,output
If it is required to set the value after the view has rendered, then you should use a view
js
App.IndexView = Em.View.extend({
setDefaulValue:function(){
this.set("controller.controllers.comboBox.model",posts[0]);
}.on("didInsertElement")
});
http://emberjs.jsbin.com/qugefipefi/1/edit?html,js,output

How to dynamically generate clickable links in ember using handlebars

I am trying to generate click able links using emberjs framework. I have the model setup correctly and I have the following handlebar template:
<script type="text/x-handlebars" data-template-name="index" >
{{#each name in model.mymodules }}
{{#link-to name 'home' }}{{name}}{{/link-to}}
{{/each
</script>
The idea is to call modulename/home on each link.
For ex: say I have 3 modules: "abc", "xyz", "123"
I want three links:
abc <a href="/abc/home">, xyz <a href="/xyz/home">, 123 <a href="/123/home">
What controller/route do I need to define for this to work.
jsfiddle:
http://jsfiddle.net/spkRa/2/
You need to make use of ember resources for dealing with this problem
Read http://emberjs.com/guides/routing/defining-your-routes/
Example of application code should be something like this. JSfidle http://jsfiddle.net/NQKvy/291/
App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_VIEW_LOOKUPS: true
});
App.Router.map(function() {
this.resource('modules', { path: '/modules' }, function() {
this.route('home', {path: ':module_name/home'});
});
});
App.IndexRoute = Ember.Route.extend({
model:function(){
return App.Modules;
}
});
App.ModulesHomeRoute = Ember.Route.extend({
model: function(params) {
//returns an object from an ember array based on the property value
return App.Module.findProperty('name',params.module_name);
},
serialize: function(model, params) {
//updates the url with the param value
return { module_name: model.get('name') };
}
});
App.Modules = Ember.A([
Ember.Object.create({name:'aaa'}),
Ember.Object.create({name:'bbb'}),
Ember.Object.create({name:'ccc'})
]);
And hadlebars code
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each}}
<li>{{name}}</li>
<li>{{#link-to 'modules.home' this}}{{name}}{{/link-to}}</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="modules/home">
This is the home of the module {{name}}
</script>

Ember Select-view error: Ember.CollectionView's content must implement Ember.Array

I want to simply render an Ember select view with the model defined in a route. Data is coming from fixtures adapter. When doing this, I receive the error: Ember.CollectionView's content must implement Ember.Array - You passed App.AuthorsController.
How can I solve this ?
See JSFIDDLE: http://jsfiddle.net/cyclomarc/frvJZ/4/
(after running the app, click on the 'Authors' link to goto the authors route with authorsController data.
CODE-HTML:
<script type="text/x-handlebars" data-template-name="application">
<h1>Ember select view</h1>
{{#linkTo 'authors'}}Authors{{/linkTo}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="authors">
{{view Ember.Select contentBinding="App.AuthorsController"}}
</script>
CODE-JS:
window.App = Ember.Application.create();
App.Router.map(function () {
this.resource('authors', { path: "/authors" });
});
App.AuthorsRoute = Ember.Route.extend({
model: function () {
return App.Author.find();
}
});
App.AuthorsController = Ember.ArrayController.extend({})
//DATA
//define model for category
App.Author = DS.Model.extend({
name: DS.attr('string'),
language: DS.attr('string')
});
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.FixtureAdapter'
});
App.Author.FIXTURES = [
{
id: 1,
name: 'Luc Verschuren',
language: 'German'
},
{
id: 2,
name: 'Patrick Burms',
language: 'Dutch'
},
{
id: 3,
name: 'Jean Demeester',
language: 'French'
}
];
Try using the content property of your App.AuthorsController having the data:
<script type="text/x-handlebars" data-template-name="authors">
{{view Ember.Select
contentBinding="content"
optionLabelPath="content.name"}}
</script>
Working jsfiddle.
Hope it helps.

createRecord called w/o params does not add object to collection

Using:
ember-1.0.0-pre.4.js
ember-data.js REVISION:11
handlebars-1.0.rc.2.js
Please have a look at this jsFiddle illustrating the described problem.
I have a list of items that are displayed in a template. The template contain a linkTo helper that let's the controller add an item to the collection and is shown as a text input on the page.
Adding the item to the collection is done by the controller:
App.TodoItem = DS.Model.extend({
title: DS.attr('string', { defaultValue: "unknown" })
});
App.Router.map(function () {
this.resource('todo_items')
});
App.TodoItemsRoute = Em.Route.extend({
model: function () {
return App.TodoItem.find();
}
});
App.TodoItemsController = Em.ArrayController.extend({
addTodoItem: function () {
App.TodoItem.createRecord();
}
});
If I want the new item to be shown is the list, I have to pass params to createRecord, otherwise the item is not visible. The same behaviour can be reproduced by using Chrome's inspector and then the item can be made visible as follows:
// Open the jsFiddle http://jsfiddle.net/bazzel/BkFYd/ and select 'result(fiddle.jshell.net) in the inspector, then:
var item = App.TodoItem.createRecord();
// Nothing visible yet.
item.set('title', 'Whatever');
// Now the text input appear with the title as its value.
Is this expected behaviour and if so, what am I missing here?
I took time to redo your example the way i feel things should be done properly with Emberjs. You should rather make sure of transaction and properly define your views and then all your issues get taken care of. So here's how i think you should do this
Define a view for the textfield to capture the value being entered or
just bind it to the model property.
Listing items and adding a new item to the list should be done in two different views and should not be mixed together
<script type="text/x-handlebars">
{{outlet}}
<div>
{{outlet 'addItem'}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="todo_items">
{{#linkTo 'todo_items.new'}}Add Todo Item{{/linkTo}}
<ul>
{{#each item in controller}}
<li>
{{#unless item.isNew}}
{{item.title}}
{{/unless}}
</li>
{{/each}}
</ul>
</script>
Define different states for listing items and adding a new one
To benefit from automatic binding of your text field value to the
model property, you need to associate an ObjectController to the TodoItemsNew route
Finally, make use of transaction to create and commit records to the store
window.App = Em.Application.create();
App.TodoItem = DS.Model.extend({
title: DS.attr('string')
});
App.TodoItem.FIXTURES = [{
id: 1,
title: 'Lorem'
}, {
id: 2,
title: 'Ipsum'
}];
App.store = DS.Store.create({
revision: 11,
adapter: DS.FixtureAdapter.create()
});
App.Router.map(function () {
this.resource('todo_items',function(){
this.route('new');
})
});
App.IndexRoute = Em.Route.extend({
redirect: function () {
this.transitionTo('todo_items');
}
});
App.TodoItemsRoute = Em.Route.extend({
model: function () {
return App.TodoItem.find();
}
});
App.TodoItemsNewRoute = Em.Route.extend({
transaction: App.store.transaction(),
setupController:function(controller) {
console.info(controller.toString());
controller.set('content',this.transaction.createRecord(App.TodoItem));
},
renderTemplate: function() {
this.render('addItem',{
into:'application',
outlet:'addItem',
})
},
events: {
addItem: function() {
this.transaction.commit();
this.transitionTo('todo_items');
}
}
});
App.TodoItemsController = Em.ArrayController.extend();
App.TodoItemsNewController = Em.ObjectController.extend();
App.TextField = Ember.TextField.extend({
insertNewline: function () {
this.get('controller').send('addItem')
}
});
Here' is a working version of the example on jsfiddle. Hopefully, i helped with this example clarify some of your issues.
Thank you Ken for answering my question. It indeed feels like a more proper of way of doing this in Ember. However, I still think it's difficult to get the hang of which objects are accessible from where...
Your example inspired me to do a rewrite of my code. I also made some changes to your approach:
I'm not sure if it's the best practice, my I don't create a store instance. Instead I define a Store class.
The content for the TodoItemsNewController is set by calling the model property on the corresponding route.
renderTemplate in the TodoItemsNewRoute only needs the outlet key.
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="todo_items">
{{#linkTo 'todo_items.new'}}Add Todo Item{{/linkTo}}
<ul>
{{outlet "addItem"}}
{{#each controller}}
<li>
{{#unless isNew}}
{{title}}
{{/unless}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="todo_items/new">
{{view Ember.TextField valueBinding="title" placeholder="Enter title"}}
window.App = Em.Application.create();
App.TodoItem = DS.Model.extend({
title: DS.attr('string', {
defaultValue: "unknown"
})
});
App.TodoItem.FIXTURES = [{
id: 1,
title: 'Lorem'
}, {
id: 2,
title: 'Ipsum'
}];
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.FixtureAdapter.create()
});
App.Router.map(function() {
this.resource('todo_items', function() {
this.route('new');
});
});
App.IndexRoute = Em.Route.extend({
redirect: function() {
this.transitionTo('todo_items');
}
});
App.TodoItemsRoute = Em.Route.extend({
model: function() {
return App.TodoItem.find();
}
});
App.TodoItemsNewRoute = Em.Route.extend({
model: function() {
return App.TodoItem.createRecord();
},
renderTemplate: function() {
this.render({
outlet: 'addItem'
});
}
});
App.TodoItemsNewView = Em.View.extend({
tagName: 'li'
});
The updated example is on jsFiddle.
Any reviews are welcome.