Ember.js: How do I access a specific item in a CollectionView? - model-view-controller

First off I want to say that I really like ember.js. I have tried both Knockout and Angular but found them a bit to obtrusive and everything had to be done their way. I feel like ember allows me a bit more freedom to structure things how you see fit. With that said I have a couple of questions.
1. I would like to do something like the following which obviously doesn't work:
<h3>{{ content.name }}</h3>
Instead I would have to create a binding:
<a {{ bindAttr href="url" }}><h3>{{ content.name }}</h3></a>
How do i create the url path in the view? I could easily create a computed property called url on the model but that feels horrible and not very MVC. Do I have to create a new view for the element or register a helper which feels a bit cumbersome?
Here's the complete code:
App = Ember.Application.create();
var sampleData = [ Ember.Object.create({ id: '123456789', name: 'John' }), Ember.Object.create({ id: '987654321', name: 'Anne' }) ]
App.itemController = Ember.ArrayController.create({
content: sampleData,
removeItem: function(item) {
this.content.removeObject(item);
}
});
App.ItemListView = Ember.View.extend({
itemDetailView: Ember.CollectionView.extend({
contentBinding: 'App.itemController',
itemViewClass: Ember.View.extend({
tagName: 'li',
url: '' // HOW TO GET '/item/123456789'
deleteButton: Ember.Button.extend({
click: function(event) {
var item = this.get('content');
App.itemController.removeItem(item);
}
})
})
})
});
<script type="text/x-handlebars">
{{#view App.ItemListView}}
<ul id="item-list">
{{#collection itemDetailView}}
<div class="item">
<a {{ bindAttr href="url" }}><h3>{{ content.name }}</h3></a>
{{#view deleteButton class="btn" contentBinding="content"}}Delete{{/view}}
</div>
{{/collection}}
</ul>
{{/view}}
</script>
2. I feel that the view "owns" the controller and not the other way around. Shouldn't the view be unaware of which controller it is hooked up to so you can reuse the view? I'm thinking about these to lines in the view:
contentBinding: 'App.itemController',
and
App.itemController.removeItem(item);
How do you structure this?
3. I realize everything is a work in progress and quite new with the name change and all but the documentation is quite unclear. The examples use the old namespace SC and there are lot of things missing on emberjs.com compared to the Sproutcore 2.0 guides, for example collections, arraycontrollers. I read somewhere here that collections will be phased out. Is that true and should I use #each instead?
Thanks for your help and for an awesome framework!

1.) If you want to use <a href="...">, you will need a computed property. It could be on your model or on a view. Another technique would be to use Ember.Button: {{#view Ember.Button tagName="a" target="..." action="..."}}...{{/view}}
2.) Typically you'll want to declare your controller binding in the template, rather than in the view. For example: {{#view App.ItemListView contentBinding="App.itemController"}}
3.) The #collection helper will likely be deprecated, so you should probably use an #each instead.

Related

How to use paths/urls/routes dynamically in vue.js/laravel components

i'm trying to write my own blog software based on vue.js/laravel for learning purposes.
Background
I'm asking myself how i write vue.js components in which the paths/urls are not hard coded. In the following example i have a post-listing component which lists all posts from the database. The json data is returned by a laravel api route (e.g. /api/posts)
In the listing i use a link to a laravel view (e.g. /posts/{id}) which shows the actual body of a specific post with {id}.
Example
In laravel's api.php route file i can give a name to a specific route and use it with route('api.posts.index'). That's dynamic enough i guess?
api.php
Route::get('', 'Api\ApiPostsController#index')->name('api.posts.index');
index.blade.php
<post-listing postsview="{{ route('web.posts.show') }}" postsapi="{{ route('api.posts.index') }}"></post-listing>
PostListing.vue
In my vue component i refer to these properties postsview and postsapi
<template>
<div>
<h2 class="title is-2">Recent posts</h2>
<ul>
<li v-for="post in posts['data']" v-bind:key="post.id">
<a :href="postsview + '/' + post.slug" v-text="post.title"></a>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ["postsapi", "postsview"],
data() {
return {
posts: []
};
},
methods: {
getPosts() {
axios.get(this.postsapi).then(response => (this.posts = response.data));
}
},
mounted() {
this.getPosts();
}
};
</script>
The question
Is there a "best-practice" way or at least a better approach? Somehow i'm not happy with this solution, but lacking experience, i don't know where to begin.
Thanks.
There are many ways to achive this, this are a few options that I know of.
1: Use blade to pass the route to the component
<component route="{{ route('route_name') }}"></component>
2: You can save a global variable with all the routes you have defined.
You can use Route::getRoutes() to get all the routes
and add it to your window on your front end
3: Use a library,
This library does exactly what you are looking for I think.
https://github.com/tightenco/ziggy
If find other options please let me know, this is a common issue for most laravel developers.

Ember.js - child nested views' controller

I'm building a simple calendar app with Ember. My views are nested this way :
<script type="text/x-handlebars" data-template-name="calendar">
{{content.monthAsString}}
{{#each day in content.days}}
{{view App.DayView contentBinding="day"}}
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name'="calendarDay">
{{content.date}}
</script>
My JS code :
App.CalendarController = Ember.ObjectController.extend({
content:App.Calendar.create(...);
oneDayHover:function(day){
}
});
App.CalendarView = Ember.View.extend({
templateName:"calendar"
});
App.CalendarDayController = Ember.ObjectController.extend({
dayHOver:function(){
//???? HOW TO ACCESS CalendarController?????
}
});
App.CalendarDayView = Ember.View.extend({
templateName:"calendarDay",
init:function(){
this._super();
this.set('controller', App.CalendarDayController.create());
},
mouseEnter:function(){
this.get('controller').dayHover();
}
});
Problem 1:
Isn't there a nicer solution than to override the init method of the view to set it's controller?
Problem 2:
How can I access the oneDayHover of CalendarController from the CalendarDayController?
Thanks in advance for the help
Update 1:
I should remark that those controllers exists in the same state. The point of the mouseenter is to display a popup on top of the CalendarDayView containing extra information.
1 - Do not assign Controllers to Views manually. Let Ember do the heavy Lifting! Have a look at Embers Router API / how to define routes. Routes will connect controllers and views and render them (Doc).
2 - If you follow point 1, your other problem will get easy with Embers way of dependency injection:
App.CalendarDayController = Ember.ObjectController.extend({
needs : ["calendar"],
dayHOver:function(){
//Access the single instance of CalendarController
var calendarController = this.get("controllers.calendar");
}
});
Update in response to Comment:
The CalendarRoute is created implicitly. Therefore all you would need to do, is modifying your template, i guess:
<script type="text/x-handlebars" data-template-name="calendar">
{{content.monthAsString}}
{{#each day in content.days}}
{{control "calendarDay" day}}
{{/each}}
</script>
As you see, i am suggesting the use of the {{control}} helper. What the code above basically says is :
"Dear Ember, please use the name 'calendarDay' to lookup
App.CalendarView and App.CalendarDayController and use them to render
the object day"
Additionally you have to tell ember, that it should not use the controller as singleton (which is the defaul behaviour):
App.register('controller:calendarDay', App.CalendarDayController, {singleton: false });
Note: I have not yet used the control helper myself, but this should be the way it works.

What is the proper way to use Ember.js controllers in this scenario?

I'm writing an Ember.js app to show a list of nested comments fetched from a CRUD RESTful API.
Half way through, I realize I'm probably misusing Ember.js and not taking advantage of its paradigms.
For instance, my Comment object looks like this:
App.Comment = Em.Object.extend({
id: null,
author: null,
text: null,
delete: function() { /* AJAX call to API here */ }
});
Is it alright to ha the delete() function as part of the model object, instead of a controller?
Another doubt I have is in my handling of states. In my template I do something like this:
{{#if view.comment.editing}}
{{view Ember.TextArea valueBinding="view.comment.text"}}
<a href="#" {{action cancelEditingComment}}>Cancel</a>
{{else}}
<p>{{view.comment.text}}</p>
<a href="#" {{action editComment}}>Edit</a>
{{/if}}
Then in my router, the editComment and cancelEditingComment actions will delegate to Comment, which has functions:
startEditing: function() { this.set('editing', true); }
cancelEditing: function() { this.set('editing', false); }
I can't help but think that I'm doing something wrong, although this kind of code seems to work.
Do you have any suggestions about how to reorganize my code, and any recommended reading that might help me with this?
From my experiences, your model shouldn't really have any business logic in it. It should just have a set of fields and maybe some computed properties if you have some complex fields that can be generated.
Your view delegating to your controller is definitely the right move for deleting. When it comes to editing though, seeing as it's only really your view that cares about this (typically), I'd be inclined to make isEditing part of the view itself. Then you can check this flag to decide whether to draw simple text or a textarea for input.
App.controller = Em.Object.create({
comments: [],
deleteComment: function(comment) {
this.get('comments').removeObject(comment);
}
});
App.CommentView = Em.View.extend({
comment: null,
isEditing: null,
delete: function() {
App.controller.deleteComment(this.get('comment'));
},
startEditing: function() {
this.set('isEditing', true);
}
});

Separating template logic from Backbone.View

I just started learning Backbone.js, and have been working on (what else) a simple to-do application. In this app, I want to display my to-do items inside of <ul id="unfinished-taks"></ul> with each task as a <li> element. So far, so simple.
According to the tutorials I have read, I should create a View with the following:
// todo.js
window.TodoView = Backbone.View.extend({
tagName: 'li',
className: 'task',
// etc...
});
This works fine, but it seems like bad practice to define the HTML markup structure of my to-do item inside of my Javascript code. I'd much rather define the markup entirely in a template:
// todo.js
window.TodoView = Backbone.View.extend({
template: _.template($("#template-task").html()),
// etc...
});
<!-- todo.html -->
<script type="text/template" id="template-task">
<li class="task <%= done ? 'done' : 'notdone' %>"><%= text %></li>
</script>
However, if I do it that way Backbone.js defaults to using tagName: 'div' and wraps all my to-do items in useless <div> tags. Is there a way to have the HTMl markup entirely contained within my template without adding unsemantic <div> tags around every view element?
If you are only planning to render the view once, you can set the el property of the view manually in .initialize():
// todo.js
window.TodoView = Backbone.View.extend({
template: _.template($("#template-task").html()),
initialize: function() {
this.el = $(this.template(this.model.toJSON())).get(0);
},
// etc
});
There are some caveats here, though:
Backbone expects the el property to be a single element. I'm not sure what will happen if your template has multiple elements at the root, but it probably won't be what you expect.
Re-rendering is difficult here, because re-rendering the template gives you a whole new DOM element, and you can't use $(this.el).html() to update the existing element. So you have to somehow stick the new element into the spot of the old element, which isn't easy, and probably involves logic you don't want in .render().
These aren't necessarily show-stoppers if your .render() function doesn't need to use the template again (e.g. maybe you change the class and the text manually, with jQuery), or if you don't need to re-render. But it's going to be a pain if you're expecting to use Backbone's standard "re-render the template" approach for updating the view when the model changes.

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

Resources