Ember.js Binding without a view - ember.js

Sorry If something like this has already been asked, but I can't find exactly what I am looking for. I'd like to preface the question by saying that I feel I have a decent understanding of content bindings. I plan on using a third party jquery carousel plugin that requires a list of img tags in a div in order to work properly. On to the actual question, let's say I have a collection of urls to images in an App controller. Assume that content will contain a list of valid urls to actual images.
App = Ember.Application.create({});
App.Controller = Em.Object.create({
content: [{url: 'http://www.google.com'}, {url: 'http://www.yahoo.com'}]
});
App.ImgView = Em.View.extend({
tagName: 'img'
});
How do I bind the src of each image to the current url without nesting another {{view}} in the #each? I've tried many combinations, but haven't been able to put my finger on the correct bindings.
<div id="foo">
{{#each App.Controller.content}}
{{view App.ImgView bindAttr src="this.url"}}
{{/each}}
</div>
The handlebar script above will error out, but I feel like it's the best why I can communicate what I am trying to do.
Thanks in advance for any help.
EDIT: After some more research I came across this issue here. Apparently srcBinding to a string was a bug in ember-0.9.4, and has been fixed in ember-0.9.5. I ended up going back to something like...
App.ImgView = Em.View.extend({
tagName: 'div'
});
<div id="foo">
{{#each App.Controller.content}}
{{#view App.ImgView contentBinding="this"}}
<img {{bindAttr src="content.url"}} />
{{/view}}
{{/each}}
</div>
so I could have a click handler on my view. I also modified the plugin to also target images inside of divs inside of #foo.
Thanks for all answers.

It seems like you want:
<div id="foo">
{{#each App.Controller.content}}
<img {{bindAttr src="url"}}>
{{/each}}
</div>
Does that work for you?

You should use srcBinding on your {{view ... }}. See example: http://jsfiddle.net/M2S3Z/
If you just want to render an image and don't need a specific Ember.View which renders the img tag, I would use ebryn's answer.
Template:
<script type="text/x-handlebars" >
<div id="foo">
{{#each App.Controller}}
{{view App.ImgView srcBinding="url"}}
{{/each}}
</div>
</script>​
JS:
App = Ember.Application.create({});
App.Controller = Em.ArrayProxy.create({
content: [{
url: 'http://www.google.com'},
{
url: 'http://www.yahoo.com'}]
});
App.ImgView = Em.View.extend({
tagName: 'img',
didInsertElement: function() {
console.log(this.get('src'));
}
});​

I would rather use something leveraging power of Ember views like this:
App.ImageView = Ember.View.extend({
tagName: 'img',
attributeBindings: ['src'],
src: url_attribute_or_variable
});

Related

Rendering to dynamic outlets

I am trying to make a list of items that when clicked, shows an edit form inline with the list item.
So far this is what I've tried:
router.js.coffee
App.Router.map ()->
#resource 'friend_management', ->
#resource 'groups', ->
#resource 'group', path: '/:group_id', ->
#route 'edit'
templates/groups.hbs
<div id="group-list">
{{#each}}
{{#view Dfw.GroupView}}
{{link-to name 'group.edit' this class=cssClass tagName='div'}}
{{outlet groupEditOutletName}}
{{/view}}
{{/each}}
</div>
<!-- it works fine if there is one outlet rendered here,
but I would prefer the outlet for the edit form rendered inline -->
templates/group/edit.hbs
{{input type='text' value=name placeholder="Group name"}}
<button {{action update}}>Update Group</button>
routes/group/edit.js.coffee
App.GroupEditRoute = Ember.Route.extend
renderTemplate: (controller, model)->
#render('group/edit', outlet: "group#{model.id}", into: 'groups')
I get the impression that Ember.js doesn't allow for dynamic named outlets, but does anyone know a work around?
One option you have would be to place the editing UI that you want to be placed inline as part of the actual view. This would remove the ability to have the action still be router based, so you wouldn't be able to have group/edit/ID, but you would be able to edit inline.
Dfw.GroupView = Ember.View.extend({
templateName: 'groupView', // or whatever you call it
isEditing: false,
click: function(evt) {
if (!this.get('isEditing')) {
this.set('isEditing', true);
}
},
actions: {
update: function (e) {
// Update code here
this.set('isEditing', false);
}
});
Then your template for the group view could be something like this:
<div {{bind-attr class=cssClass}}>
<!-- HTML that will be shown even when not editing goes here -->
{{#if view.isEditing}}
{{input type='text' value=name placeholder="Group name"}}
<button {{action view.update}}>Update Group</button>
{{/if}}
</div>
I hope this helps. While it does not use the routing, it seems as though using routing in this case wouldnt make much sense, because you are viewing all of the objects together, instead of viewing one of them and then clicking edit.
Good luck!

Set controller for template rendering

I recently decided to look into Ember.js after having spent the last two years with KO. The first thing to notice is that the complexity seems a TAD steeper but I shall prevail :)
Now, I seem to need to hardcode the controller for a certain template which seems weird:
App.IndexRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('todosList', { into: 'application' });
}
});
App.todosController = Ember.ArrayController.create({
content: [App.Todo.create(), App.Todo.create()]
});
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="todosList">
<ul id="todo-list">
{{#each todo in App.todosController.content}}
<li>
<label {{bindAttr class="todo.isCompleted"}}>{{view Ember.Checkbox checkedBinding="todo.isCompleted"}} {{todo.title}}</label>
<button {{action 'removeTodo' todo target="App.todosController"}}>Ta bort</button>
</li>
{{/each}}
</ul>
{{view Ember.TextField valueBinding="App.todosController.newTodoText"}}
<button {{action 'newTodo' App.todosController.newTodoText target="App.todosController"}}>New todo</button>
</script>
I tried setting controller: 'App.todosController' in the render() call but nothing. The #each in the view accepts nothing else than App.todosController.content which doesn't seem right. Why do I even need to explicitly state that it's the content it should read, isn't that set automatically?
Thankful for any help, Ember seems to have its niceties but in the beginning much is confusing.
Short answer first:
working jsbin: http://jsbin.com/usaluc/8/edit
Longer answer:
You had some misconceptions in your code that I've changed to be more ember-like, this results in this very simple example.
todosList template
<script type="text/x-handlebars" data-template-name="todosList">
<ul id="todo-list">
{{#each todo in controller}}
<li>
<label {{bindAttr class="todo.isCompleted"}}>
{{view Ember.Checkbox checkedBinding="todo.isCompleted"}} {{todo.title}}
</label>
<button {{action 'removeTodo' todo target="controller"}}>Remove toto</button>
</li>
{{/each}}
</ul>
{{view Ember.TextField valueBinding="newTodoText"}}
<button {{action 'newTodo' newTodoText target="controller"}}>New todo</button>
</script>
IndexRoute
When using renderTemplate to make sure the correct controller is used you should define it in the hash you are passing into the render function:
App.IndexRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('todosList', {
into: 'application',
controller: 'todosList'
});
}
});
Route map
Since you dind't post your route map, and furthermore because your are using the IndexRoute renderTemplate hook I assumed your todosList is rendered directly when visiting '/', so just to be concise here a simple router map the renders the todosList template when visiting '/'
App.Router.map(function() {
this.resource('todosList', {path: '/'});
});
TodosListRoute
Now that you have a TodosListRoute in where you want to set to correct controller content, you should hook into the setupController function and do just that:
App.TodosListRoute = Ember.Route.extend({
setupController: function(controller, model) {
var myTodos = [
App.Todo.create({title: 'Drink water', text:'foo'}),
App.Todo.create({title: 'Bring out the trash', text:'bar'})
];
controller.set('content', myTodos);
}
});
TodosListController
The TodosListController looks fairly simple so far only including the two functions newTodo and removeTodo using the title value passed from the action helper in your template:
App.TodosListController = Ember.ArrayController.extend({
newTodo: function(title) {
var todo = App.Todo.create({title: title, text:'foo'});
this.get('content').pushObject(todo);
},
removeTodo: function(todo) {
this.get('content').removeObject(todo);
}
});
Hope it helps.

Nesting existing textfield view in a new view

I have been getting a bit stuck in finding a way to reuse an ember textfield so any help would be appreciated.
What I have is (simplified here) a selection of rows like:
<div class="detailItem">Email: {{view Ember.TextField valueBinding="email"}} </div>
<div class="detailItem">Name: {{view Ember.TextField valueBinding="name"}} </div>
and instead of always wrapping in a div I'd like to make use of a new view. e.g.:
<script type="text/x-handlebars" data-template-name="detailItem">
<div class="detailItem">{{Item name}}: {{view Ember.TextField valueBinding="itemValue"}} </div>
</script>
App.DetailItemView = Em.View.extend({
templateName: 'detailItem',
name: "",
......
});
The thing I am not sure is how I get the textfield's valueBinding to link up to my controller (well actually it's content). I can obviously add another property to DetailItemView and instantiate it with that property having the values 'email' and 'name'. How though would I then pass these into the contained Ember.TextField?
Thanks for any assistance
You can do the following:
App.DetailItemView = Ember.View.extend({
templateName: 'detail_item',
classNames: ['detailItem'],
label: null,
value: ''
});
and the template:
<script type="text/template" id="detail_item">
{{view.label}}:
{{view Ember.TextField valueBinding="view.value"}}
</script>
And then use it like this:
{{view App.DetailItemView label="Email" valueBinding="email"}}
{{view App.DetailItemView label="Name" valueBinding="name"}}

Ember.js Router: Embedded resources

I'm creating an Ember application to display twitter feeds but I am having trouble with displaying individual tweets through embedded resources.
The code is as follows:
Templates
<script type="text/x-handlebars" data-template-name="tweets">
<div id="stream">
{{#each tweet in controller}}
<div class="tweet">
<p class="tweet_text">{{tweet.text}}</p>
<p> {{#linkTo "tweet" tweet}} {{tweet.id}} {{/linkTo}}</p>
</div>
{{/each}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="tweet">
<div id="detail">
{{text}}
</div>
</script>
Router
window.App = Ember.Application.create({
LOG_TRANSITIONS: true
});
App.Router.map(function(){
this.resource('tweets',function(){
this.resource('tweet',{path: ':tweet_id'})
});
});
// (1) App.Router.map(function(){
// this.resource('tweets')
// this.resource('tweet',{path: ':tweet_id'})
// });
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('tweets');
}
});
App.TweetsRoute = Ember.Route.extend({
model: function(){
var me = [];
$.getJSON("http://search.twitter.com/search.json?q=emberjs&rpp=200&count=200&callback=?",
{},
function (data) {
$.each(data.results,function(k,tweet){
var tweet = App.Tweet.create({
created_at: tweet.created_at,
from_user: tweet.from_user,
profile_image_url: tweet.profile_image_url,
text: tweet.text,
id: tweet.id
});
me.pushObject( tweet );
});
});
return me;
}
});
Objects & Controllers
App.TweetsController = Ember.ArrayController.extend({});
App.Tweet = Ember.Object.extend({
created_at: "",
from_user: "",
profile_image_url: "",
text: "",
id: 0
})
As you can see, I have a commented our router (1) which works in finding the correct tweet, and rendering it in the tweet template. However, I would like this route to be nested so that I can implement it as a Master-Detail application.
Using the LOG_TRANSITIONS, I can see that the correct routes are initialised, but I cannot get the nested resource path to render.
Any ideas would be hugely appreciated, thanks in advance.
I got this working. For anyone stuck on something similar, this is how I did it:
Templates - Changed the {{#linkTo}} "tweet"... to {{#linkTo}} "tweets.tweet"... AND added an {{outlet}}
<script type="text/x-handlebars" data-template-name="tweets">
<div id="stream">
{{#each tweet in controller}}
<div class="tweet">
<p class="tweet_text">{{tweet.text}}</p>
<p> {{#linkTo "tweets.tweet" tweet}} {{tweet.id}} {{/linkTo}}</p>
</div>
{{/each}}
</div>
{{ outlet }}
</script>
Router - Changed 'this.resource' to 'this.route'
App.Router.map(function(){
this.resource('tweets',function(){
this.route('tweet',{path: ':tweet_id'})
});
});
Caveat
I think this is a workaround and that the nested resource was the correct approach in this context. I understand that a nested route should be "a verb" or action route. I would still be grateful if anyone knows the correct approach to the question but hope the above helps others where relevant.

Break up my application.handlebars into separate templates using Ember.js and Ember.Router

I'm building a front-end (on top of Ruby on Rails) using ember.js and the ember-rails gem.
My (ember) application consists of Models, Views, Controllers and an application.handlebars template which describes my UI.
Whats the best practice to break up this application.handlebars file so that I can manage the UI? For example, I'd like to have Navigation at the top of the page.
I've tried using the Ember.Router, a separate navigation.handlebars (with NavigationView and NavigationController) the {{outlet}} helper to no avail. Here's what the Router looks like:
App.Router = Ember.Router.extend(
enableLogging: true
root: Ember.Route.extend(
index:
route: '/'
connectOutlets: (router, context) =>
router.get('applicationController').connectOutlet('navigation')
)
and the application.handlebars
<h1>Lots of HTML that I want to break up</h1>
{{outlet}}
Let me know if you need more info...thanks.
As per my Understanding, Let's suppose you want 3 sections(can be any number) Header, Content & Footer, You can do something as follows
<script type="text/x-handlebars" data-template-name="application">
{{view MyApp.HeaderView}}
{{#view MyApp.ContentView}}
{{outlet}}
{{/view}}
{{view MyApp.FooterView}}
</script>
<script type="text/x-handlebars" data-template-name="app-header">
All your Header related HTML
</script>
<script type="text/x-handlebars" data-template-name="app-content">
HTML related to content
{{yield}} //this will be explained at the end
More HTML if you want
</script>
<script type="text/x-handlebars" data-template-name="app-footer">
HTML related to footer
</script>
MyApp.HeaderView = Ember.View.extend({
templateName: 'app-header'
})
MyApp.ContentView = Ember.View.extend({
templateName: 'app-content'
})
MyApp.FooterView = Ember.View.extend({
templateName: 'app-footer'
})
MyApp.ApplicationView = Ember.View.extend({
templateName: 'application'
})
explaining {{yield}} In a nutshell, whatever is between in the block helper of a given view goes in there, In the above example for the MyApp.ContentView, the {{outlet}} defined in the {{#view MyApp.ContentView}} handlebars gets inserted at the {{yield}}
On the similar lines let me show the difference between layoutName property & templateName property,
App.someView = Ember.View.extend({
tagName: 'a',
templateName: 'a-template',
layoutName: 'a-container'
})
<script type="text/x-handlebars" data-template-name="a-template">
Hi There
</script>
<script type="text/x-handlebars" data-template-name="a-container">
<span class="container">
{{yield}}
</span>
</script>
Will result in following HTML
<a class="ember-view" id="ember235">
<span class="container ember-view" id="ember234">
Hi There
</span>
</a>
Use these concepts to split the application handlebars in your case it would be something like
{{view App.NavigationView}}
{{outlet}}
Update as per latest ember
The new ember supports partials similar to rails, now we can modify the above to use {{partial}} as follows:
{{partial "header"}}
{{outlet}}
{{partial "footer"}}
Ember when encountered this template will look for the template whose name is _header(similar to rails) and inserts the template(same goes for footer)
And If want to associate a controller we can use {{render}} helper
{{render "sidebar"}}
inserts the template whose name is sidebar at specified location in handlebars besides it also associates App.SidebarController to it,
Note: we cannot use {{render 'sidebar'}} more than once in same handlebars file.
But again if you want to use a widget like view multiple places in a given page then use {{view}} helper
For this problem, what you need to do is think about what views change and where that changes happen. If for example you have a navigation section and a main section, then think about how each of these sections change with the state of your application. Be sure to only create an {{outlet}} for dynamic content, otherwise things will get messy and the application will be slower. Then setup your templates and your router similar to the example below.
Templates:
<script type="text/x-handlebars" data-template-name="application">
<!--Your application template goes here-->
{{outlet navigation}}
{{outlet body}}
</script>
<script type="text/x-handlebars" data-template-name="navigation">
<!--Your navigation template goes here-->
</script>
<script type="text/x-handlebars" data-template-name="main-one">
<!--Your mainOne template goes here-->
</script>
<script type="text/x-handlebars" data-template-name="main-two">
<!--Your mainTwo template goes here-->
</script>
Note: You can have {{outlet}} in any of your view templates to change in more sub-states
Javascript:
window.App = Em.Application.create({
ApplicationView: Em.View.extend({
templateName: "application"
}),
ApplicationController: Em.Controller.extend({
}),
NavView: Em.View.extend({
templateName: "navigation"
}),
NavController: Em.Controller.extend({
}),
MainOneView: Em.View.extend({
templateName: "main-one"
}),
MainOneController: Em.Controller.extend({
}),
MainTwoView: Em.View.extend({
templateName: "main-two"
}),
MainTwoController: Em.Controller.extend({
})
Router: Em.Router.extend({
root: Em.Route.extend({
index: Em.Route.extend({
route: '/',
connectOutlets: function(router,context) {
router.get("applicationController").connectOutlet("navigation","nav");
router.get("applicationController").connectOutlet("body","mainOne");
}
}),
otherState: Em.Route.extend({
route: '/other-state',
connectOutlets: function(router,context) {
router.get("applicationController").connectOutlet("navigation","nav");
router.get("applicationController").connectOutlet("body","mainTwo");
}
}),
})
})
});
App.initialize();
Note: The applicationController must extend Controller and not ObjectController or ArrayController