ember {{action}} doesn't work - ember.js

I want button to call removeAlbum function in controller. But it does nothing. When i click the button nothing happens and there are no errors... What should i do to fix that?!
This is my template:
<script type="text/x-handlebars" data-template-name="albums">
{{#if App.albumsController.total}}
<div><h1>Количество альбомов: {{App.albumsController.total}}</h1></div>
{{#each content in App.albumsController}}
<div class='album'>
<div class='image'>
<a {{action showAlbum content href=true}}>
<img {{bindAttr src="content.avatarUrl"}}>
</a>
</div>
<div class='info'>
<h2>
<a {{action showAlbum content href=true}}>
{{content.title}}
</a>
</h2>
<div>{{content.description}}</div>
</div>
<div class='actions'>
<div>
<button {{action removeAlbum content target="App.albumsController"}}>Delete</button>
</div>
</div>
<div class='clear'></div>
</div>
{{/each}}
{{else}}
<div><h1>Loading</h1></div>
{{/if}}
</script>
This is my controller:
App.albumsController = Em.ArrayController.create({
content: [],
total: null,
loadAlbums: function(){
this.set('content', []);
this.set('total', null);
var self = this;
$.post(App.connection.url, {method: 'albums.getAll', params: {user_id: App.connection.userId}}, function(response){
self.set('total', response.albums.total);
response.albums.album.forEach(function(item){
var buf = App.AlbumInList.create({
id: item.id,
title: item.title,
description: item.description,
avatarUrl: item.thumbnail_video.thumbnails.thumbnail[1]._content
});
self.pushObject(buf);
});
});
},
removeAlbum: function(x){
console.log('remove it');
}
});

Try to set your target to controller instead of App.albumsController. Should solve the problem.
<button {{action removeAlbum content target="controller"}}>Delete</button>

Related

Ember CRUD application

Hello I am trying to develop stock list data along with CRUD application for assignment purpose but only stock list data is getting displayed. Here is my code. Its not displaying the other part (i.e. CRUD part) and its not showing any error as well. I am very new to ember I think it might be some silly mistake but I've tried lot of stuff but I am lost as its not throwing any error. I am not looking or any backed neither I am planning to save data. I just want to show CRUD functionality of EMBER.js some thing like this of angular
Here is my HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ember.js</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- EmberJS dependencies -->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.3.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.8.1/ember.min.js"></script>
<script src="http://builds.emberjs.com/tags/v1.0.0-beta.11/ember-data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ember-localstorage-adapter/0.3.1/localstorage_adapter.js"></script>
<!-- Lightstreamer JavaScript Client library -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js"></script>
<script src="http://demos.lightstreamer.com/commons/lightstreamer.js"></script>
<!-- EmberJS code application -->
<script src="js/stockListDemoApp.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<script type="text/x-handlebars" data-template-name="stock">
<div id="wrap">
<div id="top">
<a id="logoEmber" href="http://emberjs.com" target="_blank"><img src="images/ember_logo.png" alt="EMBERLOGO" hspace="0" border="0" /></a>
<div id="title">STOCK-LIST</div>
</div>
<table cellspacing="0" cellpadding="2" width="780" border="0" >
<thead>
<tr class="tableTitle">
<td>Name</td>
<td>Last</td>
<td>Time</td>
<td>Change</td>
<td>Bid Size</td>
<td>Bid</td>
<td>Ask</td>
<td>Ask Size</td>
<td>Min</td>
<td>Max</td>
<td>Ref.</td>
<td>Open</td>
</tr>
</thead>
<tbody>
{{#each item in model}}
<tr {{bind-attr class="item.isOdd:colOdd:colEven"}}>
<td><div {{bind-attr class="item.isOdd:stockNameOdd:stockNameEven"}}>{{item.stock_name}}</div></td>
<td>{{item.last_price}}</td>
<td>{{item.time}}</td>
<td>{{item.pct_change}}</td>
<td>{{item.bid_quantity}}</td>
<td>{{item.bid}}</td>
<td>{{item.ask}}</td>
<td>{{item.ask_quantity}}</td>
<td>{{item.min}}</td>
<td>{{item.max}}</td>
<td>{{item.ref_price}}</td>
<td>{{item.open_price}}</td>
</tr>
{{/each}}
</tbody>
</table>
<div class="disc">Simulated market data.</div>
</div>
</br>
</br>
<script type="text/x-handlebars" data-template-name="index">
<div class="jumbotron">
<h1>Welcome!</h1>
<p>This app demonstrates CRUD with validation in Ember.js</p>
</div>
</script>
<script type="text/x-handlebars" data-template-name="products">
<h1>Products</h1>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="products/index">
<table id="products_table" class="table">
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Price</th>
<th><button type="button" class="btn btn-default new-button" {{action "new"}}><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
<tbody>
{{#each product in model}}
<tr {{bind-attr id=product.htmlID}}>
<td class="name">{{#link-to "products.show" product}}{{product.name}}{{/link-to}}</td>
<td class="author">{{product.author}}</td>
<td class="price">{{product.price}}</td>
<td class="action-buttons"><button type="button" class="btn btn-default edit-button" {{action "edit" product}}><span class="glyphicon glyphicon-pencil"></span></button>
<button type="button" class="btn btn-default delete-button" {{action "delete" product}}><span class="glyphicon glyphicon-remove"></button></td>
</tr>
{{/each}}
</tbody>
</table>
<p id="products_count">Total: {{controllers.products.productsCount}} products.</p>
</script>
<script type="text/x-handlebars" data-template-name="products/show">
<h2><span class="name">{{name}}</span></h2>
<p>By <span class="author">{{author}}</span></p>
<p><strong>$<span class="price">{{price}}</span></strong></p>
<p><span class="description">{{description}}</span></p>
<p class="action-buttons"><button type="button" class="btn btn-default edit-button" {{action "edit" model}}><span class="glyphicon glyphicon-pencil"></span></button>
<button type="button" class="btn btn-default delete-button" {{action "delete" model}}><span class="glyphicon glyphicon-remove"></button></p>
<p>{{#link-to 'products' class="index-link"}}Back to products index{{/link-to}}</p>
</script>
<script type="text/x-handlebars" data-template-name="products/edit">
<h2>{{#if isNew}}New{{else}}Edit{{/if}} Product</h2>
{{#form-for controller id="form-product" wrapper="bootstrap"}}
{{#input name}}
{{label-field name text="Product"}}
{{input-field name class="form-control" autofocus="true"}}
{{#if view.showError}}
{{error-field name}}
{{/if}}
{{/input}}
{{#input author}}
{{label-field author text="Author"}}
{{input-field author class="form-control"}}
{{#if view.showError}}
{{error-field author}}
{{/if}}
{{/input}}
{{#input description}}
{{label-field description text="Description"}}
{{input-field description class="form-control"}}
{{#if view.showError}}
{{error-field description}}
{{/if}}
{{/input}}
{{#input price}}
{{label-field price text="Price"}}
{{input-field price class="form-control"}}
{{#if view.showError}}
{{error-field price}}
{{/if}}
{{/input}}
<button type="submit" class="btn btn-primary save-button" {{action "save" model}}>Save</button>
{{#if isNew}}
<button type="button" class="btn btn-default cancel-button" {{action "delete" model}}>Cancel</button>
{{else}}
<button type="button" class="btn btn-default cancel-button" {{action "cancel" model}}>Cancel</button>
<button type="button" class="btn btn-danger delete-button" {{action "delete" model}}>Delete</button>
{{/if}}
{{/form-for}}
</script>
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ember-data.js/1.0.0-beta.8/ember-data.min.js"></script>
<!-- ember-easyForm -->
<script src="http://builds.dockyard.com.s3.amazonaws.com/ember-easyForm/canary/shas/add6a40a68c8b081557a9011cf99ea255414e1b1/ember-easyForm.min.js"></script>
<!-- ember-validations -->
<script src="http://builds.dockyard.com.s3.amazonaws.com/ember-validations/canary/shas/2ff28c6ba4d227b0f863b327cdff23c381c37afb/ember-validations.min.js"></script>
</body>
</html>
and here is my app.js
App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return $.getJSON('https://ajax.googleapis.com/ajax/services/feed/load?' +
'v=1.0&num=50&q=https://news.google.com/news/feeds?output=rss&callback=?')
.then(function(data){
return data.responseData.feed.entries.map(function(entry){
var post = {};
post.title = entry.title;
return post;
});
});
}});
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter.extend({
namespace: 'ember-crud'
});
Ember.EasyForm.Config.registerWrapper('bootstrap', {
formClass: '',
fieldErrorClass: 'has-error',
inputClass: 'form-group',
errorClass: 'help-block error',
hintClass: 'help-block',
labelClass: ''
});
App.Router.map(function() {
this.resource('products', function() {
this.route('new');
this.route('show', {path: '/:product_id'});
this.route('edit', {path: '/:product_id/edit'});
});
});
App.Product = DS.Model.extend(Ember.Validations.Mixin, {
name: DS.attr('string'),
author: DS.attr('string'),
description: DS.attr('string'),
price: DS.attr('number'),
// To identify html tag for a Product.
htmlID: function() {
return 'product' + this.get('id');
}.property('id'),
validations: {
name: {
presence: true
},
price: {
presence: true,
numericality: {
greaterThanOrEqualTo: 0
}
}
}
});
App.resetFixtures = function() {
App.Product.FIXTURES = [
{
id: 1,
name: 'Ember.js in Action',
author: 'Joachim Haagen Skeie',
description: 'Ember.js in Action is a crisp tutorial that introduces the Ember.js framework and shows you how to build production-quality web applications.',
price: 44.99
},
{
id: 2,
name: 'Building Web Applications with Ember.js',
author: 'Jesse Cravens & Thomas Brady',
description: 'This guide provides example-driven instructions on how to develop applications using Ember, one of the most popular JavaScript frameworks available.',
price: 29.99
},
{
id: 3,
name: 'The Ember.js Way',
author: 'Brian Cardarella & Alex Navasardyan',
description: "Inspired by Addison-Wesley's classic The Rails Way series, The Ember.js Way crystallizes all that's been learned about Ember.js development into a start-to-finish approach that works.",
price: 39.99
},
{
id: 4,
name: 'Instant Ember.JS Application Development: How-to',
author: 'Marc Bodmer',
description: 'A practical guide that provides you with clear step-by-step examples. The in-depth examples take into account the key concepts and give you a solid foundation to expand your knowledge and your skills.',
price: 20.69
}
];
};
App.resetFixtures();
App.ProductsRoute = Ember.Route.extend({
model: function() {
return this.store.find('product');
},
actions: {
// Redirect to new form.
new: function() {
this.transitionTo('products.new');
},
// Redirect to edit form.
edit: function(product) {
this.transitionTo('products.edit', product);
},
// Save and transition to /products/:product_id only if validation passes.
save: function(product) {
var _this = this;
product.validate().then(function() {
product.save();
_this.transitionTo('products.show', product);
});
},
// Roll back and transition to /products/:product_id.
cancel: function(product) {
product.rollback();
this.transitionTo('products.show', product);
},
// Delete specified product.
delete: function(product) {
product.destroyRecord();
this.transitionTo('products');
}
}
});
App.ProductsController = Ember.ArrayController.extend({
productsCount: function() {
return this.get('model.length');
}.property('#each')
});
App.ProductsIndexRoute = Ember.Route.extend({
model: function() {
return this.modelFor('products');
}
});
App.ProductsIndexController = Ember.ArrayController.extend({
needs: ['products'],
sortProperties: ['name']
});
App.ProductsEditRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('product', params.product_id);
},
// Roll back if the user transitions away by clicking a link, clicking the
// browser's back button, or otherwise.
deactivate: function() {
var model = this.modelFor('products.edit');
if (model && model.get('isDirty') && !model.get('isSaving')) {
model.rollback();
}
}
});
App.ProductsNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('product');
},
isNew: true,
renderTemplate: function(controller, model) {
this.render('products.edit', {
controller: controller
});
},
// Roll back if the user transitions away by clicking a link, clicking the
// browser's back button, or otherwise.
deactivate: function() {
var model = this.modelFor('products.new');
if (model && model.get('isNew') && !model.get('isSaving')) {
model.destroyRecord();
}
}
});

On submit can't get data from checkbox selection

Hi in my apps I have a form with checkbox group, and I can't retrived selected at submit.
Here is some code
The form content from declare.handlebars:
<form class="declare">
<div class="hidden-fields" style="display:none">
{{view Ember.TextField valueBinding="declaration_type" class="form-control half" type="text"}}
</div>
<fieldset>
...
</fieldset>
<fieldset>
<div class="form-group">
<label>Type de support</label>
<p>
{{render 'publication/declaration_support_types' Sampick.supportTypes}}
</p>
</div>
...
</fieldset>
<div class="actions-bottom">
<button {{action "sendDeclaration" content}} class="button button-select"><i class="icon-download"></i> Confirm</button>
</div>
</form>
The handlebars code for the render of publication/declaration_support_types:
{#each }}
<label class="checkbox-inline">
{{input type="checkbox" name="publication_declaration_support_type" checked=isChecked}} {{ description }}
</label>
{{/each}}
Then I have the following controller for the render 'publication/declaration_support_types':
Sampick.PublicationDeclarationSupportTypesController = Ember.ArrayController.extend({
sortProperties: ['description'],
sortAscending: false,
itemController: 'publicationDeclarationSupportType',
selected: Ember.computed.filterBy('[]', 'isChecked', true),
selectedItems: Ember.computed.mapBy('selected', 'description')
});
Sampick.PublicationDeclarationSupportTypeController = Ember.ObjectController.extend({
isChecked: false,
toggle: function() {
this.toggleProperty('isChecked');
}
});
and finaly the route for the previous html
Sampick.PublicationDeclareRoute = Ember.Route.extend({
actions: {
sendDeclaration: function(content) {
var self = this;
if (content.get("prints") == 1) {
self.validateRecipient(content);
} else {
self.submitDeclaration(content);
}
}
}
});
My issue is that in my sendDeclaration action I can't get the selected checkbox from declarationSupportTypes using the selectedItems propertie define in the controller.
Thanks for your helps
Working fiddle: http://emberjs.jsbin.com/legozucega/1/
There was a typo in IndexRoute, action=>actions.

each vs each foo in model, differences and issue with link-to undefined

I'm trying to do a list of product items and make them so when you click the image or title it will show a single page/template with the more info, etc.
But, when ever I use {{#each product in model}} the link-to just returns an undefined.
Heres what I have
App.Router.map(function(){
this.route('about', { path: '/aboutus' } );
this.resource('products');
this.resource('product', { path: '/products/:title' } );
this.resource('contacts');
});
App.ProductsRoute = Ember.Route.extend ({
model: function(){
return App.PRODUCTS;
}
});
// Logging out Params from the Route
App.ProductRoute = Ember.Route.extend ({
model: function(params){
return App.PRODUCTS.findBy('title', params.title);
}
});
App.PRODUCTS = [
{
title: 'Flint',
price: 99,
description: 'Flint is a hard, sedimentary cryptocrystalline form of the mineral quartz, categorized as a variety of chert.',
isOnSale: true,
image: 'images/flint.png'
},
{
title: 'Kindling',
price: 249,
description: 'Easily combustible small sticks or twigs used for starting a fire.',
isOnSale: false,
image: 'images/kindling.png'
}
];
when I use this method {{#each product in model}} i get undefined
<script type='text/x-handlebars' data-template-name='products'>
<h1>Products</h1>
<ul class="list-unstyled col-md-8">
{{#each product in model}}
<li class='row m-b'>
{{#link-to 'product' this }}<img {{bind-attr src='product.image'}} class='img-thumbnail col-md-5' alt='product-image' />{{/link-to}}
<div class="col-md-7">
<h2>{{product.title}}</h2>
<p class="product-description">{{product.description}}</p>
<p><button class="btn btn-success">Buy for ${{product.price}}</button></p>
</div>
</li>
{{/each}}
</ul>
</script>
<script type='text/x-handlebars' data-template-name='product'>
<div class="row">
<div class="col-md-7">
<h2>{{title}}</h2>
<p>{{description}}</p>
<p>Buy for ${{price}}</p>
</div>
<div class="col-md-5">
<img {{bind-attr src='image'}} class='img-thumbnail img-rounded' />
</div>
</div>
</script>
but when I use just {{#each}} it returns normally BUT it warns me this: DEPRECATION: Using the context switching form of {{each}} is deprecated. Please use the keyword form ({{#each foo in bar}}) instead.
<script type='text/x-handlebars' data-template-name='products'>
<h1>Products</h1>
<ul class="list-unstyled col-md-8">
{{#each}}
<li class='row m-b'>
{{#link-to 'product' this }}<img {{bind-attr src='image'}} class='img-thumbnail col-md-5' alt='product-image' />{{/link-to}}
<div class="col-md-7">
<h2>{{title}}</h2>
<p class="product-description">{{description}}</p>
<p><button class="btn btn-success">Buy for ${{price}}</button></p>
</div>
</li>
{{/each}}
</ul>
</script>
which one should I use and how do I fix the undefined error? I'm guessing it has to do with the App.ProductRoute but can't figure it out, still new to ember :l
You should use
{{#each product in model}}
and to fix your undefined use the following:
{{#link-to 'product' product }} ...title... {{/link-to}}
When you use {{#each}} the context of this gets switched to each item in the loop, which is sometimes confusing and is being deprecated. When you use the {{#each product in model}} version, the context of each item through the loop is product and this remains whatever it was you entered each

How make a ember modal with an id?

Hi i try to make an simple ember app that's get info form a json file. App is located here:http://www.autoroben.nl/m/. Problem is i need the ember view return back an id (from the li element) which i need for handlebars. so i can pop up car info with the same jsonfile as the car list.
// MODAL
App.OpenModal = Ember.View.extend({
click: function(evt) {
var id = $(".lijst li").attr('id');
alert(id)
$('#modal').addClass('active');
}
});
the template
<script type="text/x-handlebars" id="index">
<header class="bar bar-nav">
<h1 class="title">AUTOROBEN</h1>
</header>
<div class="content">
<ul class="table-view lijst">
{{#each}}
<li class="table-view-cell media" id="{{unbound ID}}">
{{#view App.OpenModal}}
<img src="/wp-content/uploads/{{unbound featured_image.attachment_meta.file}}" class="media-object pull-left" width="80">
{{title}}
<p>{{autoinfo.details.bouwjaar}} | {{autoinfo.details.kmstand}}</p>
{{/view}}
</li>
{{/each}}
</ul>
</div>
<div id="modal" class="modal">
<header class="bar bar-nav">
{{#view App.CloseModal}}
<a class="icon icon-close pull-right nostyle" href="#"></a>
{{/view}}
<h1 class="title">{{title}}</h1>
</header>
<div class="content">
<ul class="table-view">
<li class="table-view-divider">DETAILS</li>
<li class="table-view-cell">bouwjaar: {{autoinfo.details.bouwjaar}}</li>
<li class="table-view-cell">kmstand: {{autoinfo.details.kmstand}}</li>
</ul>
</div>
</div>
</script>
json file:
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.$.getJSON('http://www.autoroben.nl/wp-json/posts/?type=autos');
}
});
Views in ember js by default get the parent context as its own context. In your case its the context of an single item in the each helper. You can access the ID from the view using the following code.
App.OpenModal = Ember.View.extend({
tagName: 'li',
classNames: ['table-view-cell', 'media'],
click: function(evt) {
alert(this.get('context.ID'));
$('#modal').addClass('active');
}
});
Here is a working bin.

In EmberJS my event triggers all the sub-views instead of just the targeted one

i'm learning EmberJS and building a comment section that allows 1 level of sub comments. I have an Ember View listing all the comments, when you click "reply" on a particular comment, it should display a textarea input for a user to write a sub-comment.
In my EmberJS code when you click "reply" it shows the textarea input for all the comments not just the specific one. Any advice would be appreciated :)
// View
App.commentsView = Em.View.create({
templateName: 'commentsTmpl',
showReply: false,
reply: function(e) {
e.view.set('showReply', true);
e.preventDefault();
}
});
App.replyCommentsView = Em.View.extend({
showReplyBinding: 'App.commentsView.showReply'
});
// Template
<script data-template-name="commentsTmpl" type="text/x-handlebars">
</h2>comment</h2>
{{#each App.commentsController}}
<div class="comment-group clearfix">
<div class="comment">
<img class="comment-pic" {{bindAttr src="userPic"}} alt="user pic">
<div class="comment-content">
{{userName}}
<span class="comment-body">{{text}}</span>
<div class="comment-actions clearfix">
<a href="#" {{action "reply"}}>Reply</a>
</div>
</div>
</div>
{{#view App.replyCommentsView}}
{{#if showReply}}
<div class="comment-reply">
<h2>sub-comment</h2>
<textarea class="txt-comment-reply" rows="2" cols="65"></textarea>
</div>
{{/if}}
{{/view}}
</div>
{{/each}}
</script>
Currently you are binding the showReply to App.commentsView which is the whole container. To be make it easy activate single comments, I'd suggest looking into a CollectionView, this way each of your comments will have their own view and you can toggle showReply on an individual comment's view.
Something like this: (Sorry, I haven't tested it)
App.commentsView = Em.View.create({
templateName: 'commentsTmpl'
});
App.CommentView = Em.View.extend({
classNames: "comment-group clearfix".w(),
showReply: false,
reply: function(e) {
e.preventDefault()
this.set("showReply", true)
}
})
// Template
<script data-template-name="commentsTmpl" type="text/x-handlebars">
</h2>comment</h2>
{{#collection contentBinding="App.commentsController" itemViewClass="App.CommentView"}}
<div class="comment">
<img class="comment-pic" {{bindAttr src="content.userPic"}} alt="user pic">
<div class="comment-content">
{{content.userName}}
<span class="comment-body">{{content.text}}</span>
<div class="comment-actions clearfix">
<a href="#" {{action "reply"}}>Reply</a>
</div>
</div>
</div>
{{#if showReply}}
<div class="comment-reply">
<h2>sub-comment</h2>
<textarea class="txt-comment-reply" rows="2" cols="65"></textarea>
</div>
{{/if}}
{{/each}}
</script>