Ember.js handling jQuery location changes - ember.js

Quick question.
I found handling site navigation (not the routing aprt, just a simple nav bar) with ember.js a little complex.
So I thought I will just code this aprt with jQuery, push history into location url and hope that Ember.js will detect this change and the router take action.
Scenario :
1) ember.js will use a DIV for rootElement and the navbar is declared in the body.
<body>
<div id="nav">
<ul><li><a>Item1</a></li></ul>
</div>
<div id="rootEmberApp"></div>
</body>
2) then a jQuery script will be bound to the links (item1) of the nav div and push changes to the URL but preventing default action without stopping the propgation (I didn't want to reload all the scripts). Something like :
$(document).ready(function(){
$("#navigation a").click(function(event){
App.router.location.setURL('/ember/listItems');
event.preventDefault();
});
3) I was hoping that Ember.js will fire at this time and take action.
I didn't succeed.
Is it silly ? Any idea how to do that ?
Thanks a lot.
Update 1 : thanks for the answer. Yes you're right. I was just not fully pleased with the solutions I tried or found about a nav bar. I will look again the todoMVC example and its use of the CollectionView. From a beginner point of view, the CollectionView seems a good way to describe (declare) the View and at the same times it's not easy to read (it's easier when the view is written with pure html and the js is bound to it ala jQuery).
Thanks again

This will probably not be a satisfactory answer, but... this is not the Ember Way. A core concept of Ember routing is that once the app loads, the source of truth is in Javascript. As you move through an Ember app, the router transitions from state to state and the URL is updated as a side effect. You're trying to turn that on it's head. It's not impossible -- you can definitely get what you're trying to do to work. However, I wanted you to know that it goes against the intention the designers had in mind.

Related

Ember router breaks on redirect to '/'

I'm having a hard time making my router understand that we are on a certain page and it should be displayed in the navigation as active. The situation is as follows:
this.route('mainRoute', function() {
this.route('list');
});
The path we are interested in is /mainRoute. Unfortunately, there are a lot of legacy links that point to /mainRoute/list. The workaround for this was to redirect from the /mainRoute/list component back to the /mainRoute component.
beforeModel() {
this.replaceWith('/mainRoute');
}
Now, my issue is that the /mainRoute navigation link will never be seen as active. I've tried adding a path for the /mainRoute ('/', '/mainRoute', 'mainRoute'), I've tried transforming it to a resource and a bunch of other things that passed my mind. But it either won't work, or will go in an infinite redirecting loop.
Any thoughts on it? Thanks so much, I really need a solution for this!
If the navigation links are {{link-to}} components. There is a current-when property you could use here. It accepts either a boolean or a string. The string is a space separated values with the route names you want this link to be active when.
From the docs
If you need a link to be 'active' even when it doesn't match the current route, you can use the
current-when argument.
<LinkTo #route='photoGallery' #current-when='photos'>
Photo Gallery
</LinkTo>
{{#link-to 'photoGallery' current-when='photos'}}
Photo Gallery
{{/link-to}}

How to prevent views from being destroyed in Ember.js

Quick note:
I don't believe this is a duplicate of Ember.js: Prevent destroying of views. Other related questions that I've found are out-of-date.
In case this becomes out-of-date later, I am using Ember 1.7.0 with Handlebars 1.3.0.
Context for the question:
As the title states, I am wondering how to transition between views without destroying them. Using queryParams does not solve my issue.
I am creating a calculator with the following nested views:
>>Calculator View
>>Report View (hasMany relationship to Calculator)
--School Partial (I am using queryParams here)
I am able to navigate between the Report views just fine without destroying my School partial, since I am using queryParams and using a displaySchoolPartial boolean to show/hide the partial. Example below:
Report template (stripped to only show the essential part):
<script type="text/x-handlebars" data-template-name="calculator/report">
...
{{#link-to "calculator.report" (query-parameters displaySchoolPartial="true")}}
{{render "_school"}}
</script>
School template (also stripped down):
<script type="text/x-handlebars" data-template-name="_school">
{{#with controllers.calculatorReport}}
<div {{bind-attr class=":schoolPartialWrapper displaySchoolPartial::hide-element"}}>
...
</div>
{{/with}}
</script>
This works as expected. Navigating between different Report views and School partials, as stated before, does not destroy the view.
The problem:
My problem comes when navigating to the Calculator view, the Report view is destroyed, which then destroys my School view. I do not want to also use queryParams to replace my Report views.
The reason I need to make sure the views aren't destroyed is because I have a select box with 3,000 schools in my School partial. It takes too long to re-render this. It would be a much better UX to simply show/hide the Report views.
Don't fight with Ember. You will lose.
Views are instantiated and rendered when needed and torn down when done.
Why do you have a 3000-element dropdown, anyway?
If you really, really want to do this, what I would suggest is putting a {{render}} on your application page, and hide it. The view will be created and rendered when the app comes up and persist as long as the app is alive. Then, in the didInsertElement of your view, do a cloneNode of that hidden element and insert it into the view's DOM somewhere. You may have to muck around getting event handlers wired up correctly.
My suggestion is not using "render" but using "partial", so you only need to drop in the template that you want. Have a control variable that set show/hide via css class. And control that variable using you controllers.
Using "partial" will allow you to have school template independent from report, thereby removing report will not affect school.
Just make sure you define the outlet and partial correctly.
Hope it helps!

How to architect an Ember.js application

It's been difficult to keep up with the evolution of Ember JS as its approached (and reached!) version 1.0.0. Tutorials and documentation have come and gone, leading to a lot of confusion about best practices and the intent of the original developers.
My question is exactly that: What are the best practices for Ember JS? Are there any updated tutorials or working samples showing how Ember JS is intended to be used? Code samples would be great!
Thanks to everyone, especially the Ember JS devs!
Mike Grassotti's Minimum Viable Ember.js QuickStart Guide
This quickstart guide should get you from zero to slightly-more-than-zero in a couple of minutes. When done, you should feel somewhat confident that ember.js actually works and hopefully will be interested enough to learn more.
WARNING: Don't just try this guide then think ember-sucks cause "I could write that quickstart-guide better in jQuery or Fortran" or whatever. I am not trying to sell you on ember or anything, this guide is little more than a hello-world.
Step 0 - Check out jsFiddle
this jsFiddle has all the code from this answer
Step 1 - Include ember.js and other required libraries
Ember.js requires both jQuery and Handlebars. Be sure those libraries are loaded before ember.js:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0-rc.1/ember.js"></script>
Step 2 - Describe your application's user interface using one or more handlebars templates
By default ember will replace body of your html page using content of one or more handlbars templates. Someday these templates will be in separate .hbs files assembled by sprockets or maybe grunt.js. For now we will keep everything in one file and use script tags.
First, let's add a single application template:
<script type="text/x-handlebars" data-template-name="application">
<div class="container">
<h1>Ember.js is easy?<small> Minimum Viable Ember.js QuickStart Guide</small></h1>
<p>{{message}}</p>
</div>
</script>
Step 3 - Initialize your ember application
Just add another script block with App = Ember.Application.create({}); to load ember.js and initialize your application.
<script type='text/javascript'>
App = Ember.Application.create({});
</script>
That's all you need to create a basic ember application, but it's not very interesting.
Step 4: Add a controller
Ember evaluates each handlebars templates in the context of a controller. So application template has a matching ApplicationController. Ember creates is automatically if you don't define one, but here let's customize it to add a message property.
<script type='text/javascript'>
App.ApplicationController = Ember.Controller.extend({
message: 'This is the application template'
});
</script>
Step 5: Define routes + more controllers and templates
Ember router makes it easy to combine templates/controllers into an application.
<script type='text/javascript'>
App.Router.map(function() {
this.route("index", { path: "/" });
this.route("list", { path: "/list" });
});
App.IndexController = Ember.Controller.extend({
message: 'Hello! See how index.hbs is evaluated in the context of IndexController'
});
App.ListRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', ['angular.js', 'backbone.js', 'ember.js']);
}
});
</script>
To make this work, we modify our the application template by adding an {{outlet}} helper. Ember router will render appropriate template into the outlet depending on user's route. We will also use the {{linkTo}} helper to add navigation links.
<script type="text/x-handlebars" data-template-name="application">
<div class="container">
<h1>Ember.js is easy?<small> Minimum Viable Ember.js QuickStart Guide</small></h1>
<p>{{message}}</p>
<div class="row">
{{#linkTo index class="span3 btn btn-large btn-block"}}Home{{/linkTo}}
{{#linkTo list class="span3 btn btn-large btn-block"}}List{{/linkTo}}
</div>
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="list">
<h3 class="demo-panel-title">This is the list template</h3>
<ul>
{{#each item in content}}
<li>{{item}}</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="index">
<h3 class="demo-panel-title">This is the index template</h3>
<p>{{message}}</p>
</script>
Done!
A working example of this application is available here.
You can use this jsFiddle as a starting point for your own ember apps
Next Steps...
Read the Ember Guides
Maybe buy the Peepcode screencast
Ask questions here on Stack Overflow or in ember IRC
For reference, my original answer:
My question is for any Ember.js expert, and certainly the respective tutorial authors: When should I use design patterns from one tutorial, and when from the other?
These two tutorials represent best practices at the time they were written. For sure there is something that can be learned from each, both are sadly doomed to become out of date because ember.js is moving very quickly. Of the two, Trek's is far more current.
What components of each are personal preferences, and what components will prove essential as my app matures?
If you are developing a new ember application I would not recommend following the Code Lab approach. It is just too out-of-date to be useful.
In Code Lab's design, Ember seems to be closer to existing within the application (even though it is 100% of his custom JS), whereas Trek's application seems to live more within Ember.
Your comment is bang-on. CodeLab is making taking advantage of core ember components and accessing them from global scope. When it was written (9 months ago) this was pretty common but today best-practice for writing ember applications is much closer to what Trek was doing.
That said, even Trek's tutorial is becoming out-of-date. Components that were required ApplicationView and ApplicationController are now generated by the framework itself.
By far the most current resource is the set of guides published at http://emberjs.com/guides/
- they have been written from the ground up over the last few weeks and reflect the latest (pre-release) version of ember.
I'd also check out trek's wip project here: https://github.com/trek/ember-todos-with-build-tools-tests-and-other-modern-conveniences
EDIT:
#sly7_7 : I'd also give an other example, using ember-data https://github.com/dgeb/ember_data_example
There is an important project that both new and veteran Ember.js developers should take advantage of:
Ember-CLI
While it does require some comfort level with the command line, you can generate a modern Ember project with community recommended best practices in a matter of seconds.
While it is beneficial to setup an Ember.js project the hard way as in Mike Grassotti's answer, you should not be doing that for production code. Especially when we have such a powerful and easy to use project like Ember-CLI to show us the Yehuda approved happy path.
There is 30 minutes fresh screencast made by #tomdale: https://www.youtube.com/watch?v=Ga99hMi7wfY
I would highly recommend using Yeoman and its accompanying ember generator. Out of the box you get all the tools you need to develop, test and prepare an app for production. As an added bonus, you'll be able to split your view templates into multiple files and start with an intelligent directory structure that will facilitate you in creating a maintainable codebase.
I've written a tutorial on getting it up and running in about 5 minutes. Just install node.js and follow along here
The Fire Up Ember - Peepcode screencast is worth a watch.
Also go through this free tutorial titled Let’s Learn Ember from Tuts+ Premium. Its free because its from their free courses series.
This course, as the Tuts guys call it, is divided into fourteen easy to follow chapters.
I hope this helps.
Regards,
I prefer the charcoal yeoman approach. It gives you a ton of stuff out of the box including:
a nice folder architecture using a 'module' approach.
neuter
live reload
minify
uglify
jshint
and more.
and its super easy to setup, just run yo charcoal to create an app then yo charcoal:module myModule to add a new module.
more info here: https://github.com/thomasboyt/charcoal
I've just created a Starter Kit, if you would like to use the latest EmberJS with Ember-Data, with Emblem template engine. All wrapped in Middleman, so you can develop with CoffeeScript. Everything on my GitHub: http://goo.gl/a7kz6y
Although outdated Flame on Ember.js
is still a good tutorial for someone looking at ember for the first time.
I've started building a series of videos that start from before Ember and build towards using Ember in anger in serious use-cases for real-world things.
If you're interested in seeing this hit the light of day (I'm more than happy to eventually put it public if there's interest) you should definitely go over to the post I made and hit "like" (or just comment here, I guess):
http://discuss.emberjs.com/t/making-ember-easier-to-approach-aka-crazy-screencasts-videos-that-will-stick-in-your-mind-for-learning-ember/5284
I'm super keen to make it to help the community flourish, but also to help people learn how to build standard web sites in an easy way.

Cant figure out views rendering (they are prepended right before /body)

First my apologies: Im very new to ember.js and struggling so far.
I have a pretty basic app written and I've been using this as my main guide: http://trek.github.com/
My biggest issue right now is figuring out how to deal with Views, specifically the rendered HTML and where it appears in the DOM. It appears, at least with my app currently, the DOM elements are created and inserted into the page but right before /body. So everything just loads below the footer of my main site design.
Doesnt seem to matter where placement of the script templates are in relation to the page, or anything like that??
Is there a way to render views to an existing container div or something? Am I thinking about this wrong? Im used to working with jsRender where I have templates setup, but they typically rendered to an in-memory string that I then needed to insert into an existing container like $('#containerDiv').html(myRenderedHtmlFromATemplate);
Thanks for any help or guidance with this!
Ember will want its views to be hierarchical in the DOM so it can rely on event propagation. You probably noticed a <div class="ember-application"> that gets injected, and then all of your views are rendered inside of that.
You can specify the rootElement when you create your Application. The application will be created inside that element and leave the rest of the DOM untouched. If you don't specify that rootElement, then Ember will insert itself right before </body> as you observed.
Example:
window.MyApp = Ember.Application.create({
rootElement: "#containerDiv"
});
Without seeing code it isn't completely clear what exactly is going on, but, I do not see you mention anything about outlets so I assume that might be your problem.
Check out this url on outlets: http://emberjs.com/guides/outlets/
tuxedo25 has the best solution. If you are using StateManager you can also use the following:
App.StateManager = Ember.StateManager.create({
rootElement: '.content',
initialState: 'initial',
initial: Ember.ViewState.create({
route: 'initial',
view: Ember.View.create({ templateName: 'initial' })
})
});

archetypal code from Ember's own site not working -- any ideas?

There are several extensive code examples on a tutorial page at the ember web site that are all failing in a specific way. As this is supposed to be archetypal ember code ostensibly to direct newcomers how to code in ember, I am at a loss. Could someone who knows ember have a look at the code. (An example is directly above that bookmark I listed, and includes both the templates and js.
Specifically what's happening is that the main root page template has an outlet 'footer' that's only written to by the subpages, but when you navigate back to the home (root/index) page, that outlet still has the info from the subpages showing, which it shouldn't. The same thing is happening with the template called 'traversal' whose outlet is only written to by the subpages, but that outlet is also still showing info in it when you navigate back to the root.
I did run across a function disconnectOutlet in the API docs, but it says you shouldn't hardly ever have to use it, and its not in the example code. I tried it - evidently not actually in the api anymore.
If you want to run that code above you'll need the following from the ember site:
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/jquery-1.7.2.min.js"></script>
<script src="js/libs/handlebars-1.0.rc.1.js"></script>
<script src="js/libs/ember-1.0.pre.min.js"></script>
As you mentioned, disconnectOutlet was added by this pull request. You can use it to remove an outletView (by name) from a controller. For example, remove myOutletViewName from applicationController when exiting a certain route:
aRoute: Ember.Route.extend({
exit: function(router) {
router.applicationController.disconnectOutlet('myOutletViewName')
}
})
Note that if you use {{outlet}} in your template, without specifying a name, the default name is view so you do:
router.applicationController.disconnectOutlet('view')