Binding events to views - Firing uneven number of times - javascript

I have UserModel: UserView and UserCollection: UserCollectionView. With this, I am trying to bind a click event to the UserView (I am doing this in UserView). So, this is the code I have:
var root = 'http://localhost:5000/api/v1';
var app = {};
// Backbone Model
app.UserModel = Backbone.Model.extend({
defaults: {
// urlRoot: root + '/users',
name: 'Default Name',
email: '30',
username: 'default_username'
},
initialize: function() {
this.set({
id: this.get('username')
});
console.log('User model \'' + this.id + '\' has been initialized.');
},
// parse: function(data) {
// console.log('Model parse funciton called');
// return data;
// }
});
// Backbone Model View
app.UserView = Backbone.View.extend({
// el: '#users-list',
// tagName: 'div',
el: '.user-box-wrapper',
events: {
'click .user-data': 'userClicked'
},
userClicked: function(ev) {
console.log("User selected");
// console.log(ev.currentTarget);
},
template: _.template($('#connections-user-template').html()),
initialize: function() {
this.render();
},
render: function() {
$('#users-list').append(this.template(this.model.toJSON()));
// this.$el.append( this.template( this.model.toJSON()));
console.log('User view is rendered');
}
});
// Backbone Collection
app.UserCollection = Backbone.Collection.extend({
model: app.UserModel,
url: root + '/users',
initialize: function() {
// this.fetch();
},
parse: function(data) {
// console.log(data.data);
return data.data;
}
});
// Backbone Collection View
app.UserCollectionView = Backbone.View.extend({
el: '#users-list',
template: _.template($('#connections-template').html()),
initialize: function() {
this.connections = new app.UserCollection();
var self = this;
this.connections.fetch().done(function() {
self.render();
});
},
render: function() {
console.log('User collection view is rendered');
this.$el.html(this.template());
// this.$el.append( this.template( this.model.toJSON()));
this.connections.each(function(user) {
console.log('User : ' + user.get('id'));
var userView = new app.UserView({
model: user
});
// userView.model.fetch();
// userView.render();
});
}
});
var connectionsView = new app.UserCollectionView();
The JSON data actually returns 14 objects (or UserModels in this case). The problem is, if I click the first user view, it is triggered 13 times, and the second view click is triggered 12 times and so on, the last view click event not being triggered at all when clicked.
The individual UserViews are rendered once each, however (that's what I think at least). Can someone please explain what the problem here is and what exactly is happening here?
P.S. - I am aware of the workaround of binding the events in the CollectionView.
Edit 1
This is the DOM structure:
<!doctype html>
<html>
<head>
<title>Hey there</title>
<link rel="stylesheet" href="../static/css/normalize.css">
<link rel="stylesheet" href="../static/css/index.css">
<script src="/static/js/jquery-2.2.0.js"></script>
<script src="/static/js/underscore-1.8.3.js"></script>
<script src="/static/js/backbone-1.2.3.js"></script>
</head>
<body>
<header id="top">
<div id="logo-wrapper">
<img src="../static/img/logo.png" alt="Logo" id="logo">
</div>
<div id="top-links">
<div id="top-profile-box" class="toplink">
<div id="top-profile-data-box">
<div id="top-profile-data-name">Kevin Isaac</div>
<div id="top-profile-data-passion">Writer</div>
</div>
<img id="top-profile-image" src="../static/img/user1.jpg" alt="">
</div>
<div id="notification-icon" class="toplink"></div>
<div id="top-message-icon" class="toplink"></div>
<div id="logout-icon" class="toplink"></div>
</div>
</header>
<div id="middle">
<nav id="side-nav">
<div id="side-nav-top">
<div class="side-nav-link" id="side-nav-home-link">
<div class="side-nav-link-img"></div>
<div class="side-nav-link-title">Home</div>
</div>
<div class="side-nav-link" id="side-nav-profile-link">
<div class="side-nav-link-img"></div>
<div class="side-nav-link-title">Profile</div>
</div>
<div class="side-nav-link" id="side-nav-messages-link">
<div class="side-nav-link-img"></div>
<div class="side-nav-link-title">Message</div>
</div>
<div class="side-nav-link" id="side-nav-account-link">
<div class="side-nav-link-img"></div>
<div class="side-nav-link-title">Account</div>
</div>
</div>
</nav>
<div id="main-content">
<!-- Start of page specific HTML -->
<div id="content-title">
<div class="content-subtitle" id="connections">Connections</div>
<div class="content-subtitle" id="followers">Followers</div>
<div class="content-subtitle" id="followings">Followings</div>
</div>
<div id="content-body">
<div id="users-box">
<div id="users-list">No connection</div>
<!-- Backbone Template Starts -->
<script type="text/template" id="connections-template"></script>
<script type="text/template" id="connections-user-template">
<div class="user-box-wrapper">
<div class="user-box">
<div class="user-pic-wrapper">
<img src="/static/img/user1.jpg" alt="">
</div>
<div class="user-data" id="boox">
<div class="user-name"><%= name %></div>
<div class="user-passion"><%= username %></div>
<div class="user-city"><%= email %></div>
</div>
</div>
</div>
</script>
<!-- Backbone Template Ends -->
<div id="users-side-box">
<div id="users-box-search">
<input id="user-search" type="text" name="">
</div>
<div id="user-metadata">
<div id="metadata-user-top-box">
<div id="metadata-user-image-wrapper">
<img src="/static/img/user1.jpg" alt="">
</div>
<div id="metadata-user-name-box">
<div id="metadata-name">Name's Bond</div>
<div id="metadata-passion">Assassin</div>
</div>
</div>
<div id="metadata-user-bottom-box">
<div class="metadata-user-attribute">
<span class="metadata-property">Studied at: </span>
<span class="metadata-value">Karunya University </span>
</div>
<div class="metadata-user-attribute">
<span class="metadata-property">Native City: </span>
<span class="metadata-value">London</span>
</div>
<div class="metadata-user-attribute">
<span class="metadata-property">Website: </span>
<span class="metadata-value">www.007.com</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End of page specific HTML -->
</div>
<aside id="main-aside">
Aside one two therr
</aside>
</div>
<script src="../static/js/index.min.js"></script>
</body>
</html>

There are many issues with your code.
Main problem is that, all your userView's are pointing to the same selector, and the element matching this selector .user-box-wrapper is inside the view template - So whenever you create a new userView, it'll add a new event listener to .user-box-wrapper present in all existing userViews, but not to itself. So your first userView will have n-1 events handlers registered to it while last one has none (n being total number of userViews). View element is not supposed to be part of template, template is supposed to be added to the view element.
When your view will have multiple copies of itself, don't define el option, let backbone create a new element for each instance of the view. You can customize the properties of this element.
Another issue is that you are not appending the userView template to your userView element, but something else outside it ($('#users-list'). So clicking the template won't trigger the event handler (in your case this is why you're last userView doesn't fire it's event. It was bound to all other existing views because common selector was provided by el)
You should try to avoid global selectors like $('#users-list') from within a view. In this case you can append the userView to #users-list from within userCollectionView who's el points to #users-list.
Your code should be:
var root = 'http://localhost:5000/api/v1';
var app = {};
// Backbone Model
app.UserModel = Backbone.Model.extend({
defaults: {
// urlRoot: root + '/users',
name: 'Default Name',
email: '30',
username: 'default_username'
},
initialize: function() {
this.set({
id: this.get('username')
});
console.log('User model \'' + this.id + '\' has been initialized.');
}
});
// Backbone Model View
app.UserView = Backbone.View.extend({
className: 'user-box-wrapper',
/*--^-- creates a new div with this class for each user*/
template: _.template($('#connections-user-template').html()),
events: {
'click .user-data': 'userClicked'
},
initialize: function() {
this.render();
},
render: function() {
this.$el.append( this.template( this.model.toJSON()));
console.log('User view is rendered');
},
userClicked: function(ev) {
console.log("User selected");
// console.log(ev.currentTarget);
}
});
// Backbone Collection
app.UserCollection = Backbone.Collection.extend({
model: app.UserModel,
url: root + '/users',
initialize: function() {
// this.fetch();
},
parse: function(data) {
// console.log(data.data);
return data.data;
}
});
// Backbone Collection View
app.UserCollectionView = Backbone.View.extend({
el: '#users-list',
template: _.template($('#connections-template').html()),
initialize: function() {
this.connections = new app.UserCollection();
var self = this;
this.connections.fetch().done(function() {
self.render();
});
},
render: function() {
this.$el.html(this.template());
console.log('User collection view is rendered');
this.connections.each(function(user) {
console.log('User : ' + user.get('id'));
var userView = new app.UserView({
model: user
});
this.$el.append(userView.el); /*append child view here*/
},this);
}
});
var connectionsView = new app.UserCollectionView();

The main problem is that you are rendering all UserView views in the same container:
$('#users-list').append(this.template(this.model.toJSON()));
This is why the click event selector('click .user-data') is selecting the other UserView buttons and firing it's clicks too.
You didn't ask but... here it goes some suggestions:
Do not call render from the initialize function;
Avoid defining the el;
Avoid adding the view content outside the view using $. Use
this.$el instead;
NEVER forget to return this; at you render functions.
Here is a jsfiddle with what I think you want:
https://jsfiddle.net/Neviton/n52j873u/

Related

Child outlet goes empty when I refresh the url with id from {{link-to}} in Emberjs

I have a weird issue, the child outlet goes empty whenever I will refresh the page with the id. I have a list generated by {{link-to}} helper.
<script type="text/x-handlebars" id="twod">
<div class="row">
<div class="span4">
<img src="/img/2DPipeline.jpg" />
</div>
<div class="span3">
<h4>People with Roles</h4>
<div class="row">
<div class="span2">
<ul>
{{#each item in model}}
<li>{{#link-to 'twoduser' item}}{{item.firstname}} {{/link-to}}</li>
{{/each}}
</ul>
</div>
<div class="row">
<div class="span">
{{outlet}}
</div>
</div>
</div>
</div>
</script>
Here's the twoduser template,
<script type="text/x-handlebars" data-template-name="twoduser">
<div class="row">
<div class="span3">
Full Name: {{firstname}}{{lastname}}
EMail: {{email}}
</div>
</div>
</script>
App.js,
App.Router.map(function() {
this.resource('twod', function() {
this.resource('twoduser', {
path : ':user_id'
});
});
this.resource('threed');
});
App.TwoduserRoute = Ember.Route.extend({
model : function(params) {
return App.Twod.findBy(params.user_id);
}
});
App.Twod.reopenClass({
findAll : function() {
return new Ember.RSVP.Promise(function(resolve, reject) {
$.getJSON("http://pioneerdev.us/users/index", function(data) {
var result = data.users.map(function(row) {
return App.Twod.create(row);
});
resolve(result);
}).fail(reject);
});
},
findBy : function(user_id) {
var user = App.Twod.create();
$.getJSON("http://ankur.local/users/byId/" + user_id, function(data) {
user.setProperties(data.user);
});
user.set("user_id", user_id);
return user;
}
});
App.TwodRoute = Ember.Route.extend({
model : function() {
return App.Twod.findAll();
}
});
Selecting each one individually works fine and fills the child outlet, but when I refresh it, it goes blank.
Any ideas what might be causing the issue?
I can see two possible problems.
The first is that your URLs are different between findAll and findBy. Was that intentional?
The second is that findAll returns an Ember promise (Ember.RSVP.Promise), but findBy does not.
[UPDATE] : Based on the JSBin in the comments : http://jsbin.com/iPUxuJU/1/
The problem here is that the API endpoint is returning an array in the user response. It currently looks like this:
{user : [{ ... }] }
Ideally it would look like this :
{user : {....} }
You could change the API endpoint, or you could update your code to pull the first element from that array. Instead of :
user.setProperties(data.user);
You could do :
user.setProperties(data.user[0]);
Here's an altered JSBin : http://jsbin.com/oquBoMA/1#/twod/2

Loading a single model with Ember.js

I'm trying to write a pretty simple app: I have some games (say chess, tictactoe... whatever), and there are several boards of each game. I want to show a list of games, and then show a list of boards when you click on a game.
But I'm facing a lot of problems. I'll first describe them, and I'll paste the code after that:
The list of games is correctly shown. No problem here.
When I click a game, I get this error:
Uncaught Error: assertion failed: an Ember.CollectionView's content must implement Ember.Array. You passed <(generated game controller):ember237>
BUT if I press F5 or write the URL manually, everything works fine. And I have no idea why.
UPDATE: I've seen that if I change the games template, changing the {{#linkTo}} with a hand-written link, everything works OK:
This is the non-working linkTo: {{#linkTo 'game' game}}{{game.name}}{{/linkTo}}. It builds the URL correctly, but it fails when I click on it.
This is a hand-written <a> tag: {{game.name}}. It works perfectly.
The Url of each board should follow this format:
/games/1/boards/5
But when I write the {{#linkTo 'board' board}} what I get is:
/games/undefined/boards/5
Here is the code (You can see a "working" copy here in JBin. But it's not functional, because it relays on a local REST app):
The Router:
MGames.Router.map(function () {
this.resource('games', function () {
this.resource ('game', {path: '/:game_id'}, function () {
this.resource('board', {path: '/boards/:board_id'});
});
});
});
MGames.IndexRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('games');
}
});
MGames.GamesRoute = Ember.Route.extend ({
model: function() {
return MGames.Game.findAll();
}
});
MGames.GameRoute = Ember.Route.extend ({
model: function(params) {
return MGames.Board.findAllByGame(params.game_id);
}
});
MGames.BoardsRoute = Ember.Route.extend ({
model: function(params) {
return this.modelFor('game').then(
function (game) {
return MGames.Board.find(game.get('id'), params.board_id);
}
);
}
});
The models:
MGames.Game = Ember.Object.extend({
id: null,
name: null,
icon: null
});
MGames.Game.reopenClass({
findAll: function() {
var url = [MGames.GAMES_API_URL];
url.push ('games');
url = url.join('/');
var result = Ember.ArrayProxy.create({ content: [] });
$.getJSON(url).then (
function (response) {
response.forEach(function (child) {
result.pushObject (MGames.Game.create(child));
});
}
);
return result;
},
find: function (id) {
var url = [MGames.GAMES_API_URL];
url.push ('games');
url.push (id);
url = url.join('/');
var game = MGames.Game.create({ isLoaded: false });
$.getJSON(url).then (
function(response) {
game.setProperties(response);
game.set('isLoaded', true);
}
);
return game;
}
});
MGames.Board = Ember.Object.extend({
id: null,
name: null,
owner: null,
game: null,
is_public: null,
created_at: null
});
MGames.Board.reopenClass({
findAllByGame: function (game) {
var url = [MGames.GAMES_API_URL];
url.push ('games');
url.push (game);
url.push ('boards');
url = url.join('/');
var result = Ember.ArrayProxy.create({ content: [] });
$.getJSON(url).then (
function (response) {
console.log (response);
response.forEach(function (child) {
result.pushObject (MGames.Board.create(child));
});
}
);
return result;
},
find: function (game, board) {
url = [MGames.GAMES_API_URL];
url.push ('games');
url.push (game);
url.push ('boards');
url.push (board);
url = url.join('/');
var result = MGames.Board.create();
$.getJSON(url).then (
function(response) {
result.setProperties(response);
}
);
return result;
}
});
And the template:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MGames</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<script type="text/x-handlebars">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">{{#linkTo 'index' class="brand"}}MGames{{/linkTo}}</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" id="games">
<div class="row">
<header id="header">
<h1>Games</h1>
</header>
<ul>
{{#each game in controller}}
<li>
{{#linkTo 'game' game}}{{game.name}}{{/linkTo}}
</li>
{{/each}}
</ul>
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" id="game">
<div class="row">
<div class="span3" id="boards">
<header id="header">
<h1>Boards</h1>
</header>
<ul id="board-list">
{{#each board in controller}}
<li>
{{#linkTo 'board' board}}{{board.name}}{{/linkTo}}
</li>
{{/each}}
</ul>
</div>
<div class="span9">
{{outlet}}
</div>
</div>
</script>
<script type="text/x-handlebars" id="board">
<header id="header">
<h1>{{game.name}} - {{name}} <small>{{owner.nickname}}</small></h1>
</header>
</script>
<script src="js/libs/jquery.js"></script>
<script src="js/libs/bootstrap.js"></script>
<script src="js/libs/handlebars.js"></script>
<script src="js/libs/ember.js"></script>
<script src="js/application.js"></script>
<script src="js/router.js"></script>
<script src="js/models/game.js"></script>
<script src="js/models/user.js"></script>
</body>
</html>
Ok, I finally figured out the problem. In my gameRoute I wrote this:
MGames.GameRoute = Ember.Route.extend ({
model: function(params) {
return MGames.Board.findAllByGame(params.game_id);
}
});
It worked when I write the URL directly in the browser bar, because Ember calls the model function, but when following a {{#linkTo}} the model is the one passed as parameter, so the modelfunction isn't called.
So the working code is this one (a little bit simplified):
MGames.GameRoute = Ember.Route.extend ({
model: function (params) {
// This is only called when loading the URL directly,
// not following a link. We load the game, and in the
// setupController we'll load the boards.
return MGames.Game.find(params.game_id);
},
setupController: function(controller, game) {
// This is *always* called, so we load the boards
model = MGames.Board.findAllByGame(game.id);
controller.set('model', model);
}
});
The board route that you are linking to has 2 dynamic segments, but you are providing only one. You need to change to,
{{#linkTo 'board' game board}}The board{{/linkTo}}
The undefined error is probably due to the ArrayController not getting a board as the corresponding game id is being passed as undefined. The above change should fix that too.

How to bind data from two tables in PhoneJs?

I have two tables:
nom_articole { id(PK), denumire, nom_um_id(FK) }
nom_um { id(PK), simbol, denumire }
I want to display:
nom_articole.id
nom_articole.denumire
nom_um.simbol
My html code:
<div data-options="dxView : { name: 'nom_articoleDetails', title: 'Nom_articole' } " >
<div data-options="dxContent : { targetPlaceholder: 'content' } " >
<div data-bind="dxScrollView: { }">
<h2 data-bind="text: nom_articole.denumire"></h2>
<div class="dx-fieldset">
<div class="dx-field">
<div class="dx-field-label">ID</div>
<div class="dx-field-value" data-bind="text: nom_articole.id"></div>
</div>
<div class="dx-field">
<div class="dx-field-label">Denumire</div>
<div class="dx-field-value" data-bind="text: nom_articole.denumire"></div>
</div>
<div class="dx-field">
<div class="dx-field-label">U.M.</div>
<div class="dx-field-value" data-bind="text: ????????????????"></div>
</div>
</div>
<div data-options="dxContentPlaceholder : { name: 'view-footer', transition: 'none' } " ></div>
</div>
</div>
My Javascrip code:
MobileApplication.nom_articoleDetails = function(params) {
return {
id: params.id,
//nom_um: new MobileApplication.nom_umViewModel(),
nom_articole: new MobileApplication.nom_articoleViewModel(),
handleDelete: function() {
DevExpress.ui.dialog.confirm("Are you sure you want to delete this item?", "Delete item").then($.proxy(function (result) {
if (result)
this.handleConfirmDelete();
}, this));
},
handleConfirmDelete: function() {
MobileApplication.db.nom_articole.remove(params.id).done(function() {
MobileApplication.app.navigate("nom_articole", { target: "back" });
});
},
viewShown: function() {
nom_articoleDetails = this;
MobileApplication.db.nom_articole.byKey(params.id).done(function(data) {
nom_articoleDetails.nom_articole.fromJS(data);
});
}
};
This code was generated by Devexpress multi-channel application wizard.
From the information you gave, and provided that nom_articole and nom_um share the same key, the code would be:
viewShown: function() {
// ... your code ...
MobileApplication.db.nom_um.byKey(params.id).done(function(data) {
nom_articoleDetails.nom_um.fromJS(data);
});
}
You uncomment the nom_um member and use text: nom_um.simbol as the binding text in the view.
Update:
To load an object by foreign key, you have two options. The first is cascading fetches:
MobileApplication.db.nom_articole.byKey(19).done(function (data) {
nom_articoleDetails.nom_articole.fromJS(data);
MobileApplication.db.nom_um.byKey(data.nom_um_id).done(function(data) {
nom_articoleDetails.nom_um.fromJS(data);
});
});
The second will work if your data service is properly configured OData. In this case you may use the expand feature:
MobileApplication.db.nom_articole.byKey(19, { expand: "nom_um" }).done(function (data) {
// data will contain a nested object
});
P.S. DevExpress provides Support service, and in case you cannot find the right answer here, you can ask them and share the solution.

Backbone.js adding sub-view elements to parent-view's element

I have a collection view and a model view, like so:
EventListView
|-- EventView
EventListView must display many EventViews in a one-to-many relationship. I am using the underscore _.template() function to build my views templates.
Here is my EventView template:
<h1>
<span class="date"><%= prefix %><%= dateString %></span>
<span class="title"><%= title %></span>
</h1>
<div class="caption"><%= caption %></div>
My EventView render method:
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
And here is my EventListView template:
<h1>
<% if(typeof(title) != "undefined") { print(title) } %>
</h1>
<%= events %>
And it's render method:
// this._EventViews is an array of eventView objects
render: function() {
var templateData = {
events: _.reduce(this._EventViews, function(memo, eventView) { return memo + eventView.$el.html(); }, "")
}
this.$el.html(this.template(templateData));
return this;
}
The problem I am having is that eventView.$el.html() contains only the HTML in my template, but I need to take advantage of the tagName, className and id attributes that Backbone views support.
Consider if I set up EventView like so:
return Backbone.View.extend({
model: EventModel
, tagName: 'article'
, className: 'event'
, template: _.template(templateText)
, render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
I want to insert:
<article class="event" id="someID342">
<h1>
<span class="date">01/02/2010</span>
<span class="title"></span>
<div class="caption></div>
</h1>
</article>
but eventView.$el returns:
<h1>
<span class="date">01/02/2010</span>
<span class="title"></span>
<div class="caption></div>
</h1>
How do I insert the entire eventView element? Not just it's innerHTML.
Just reserve placeholder in your EvenListView's template
<h1><%- title %></h1>
<div class="js-events"></div>
And then render and append child views
render: function() {
this.$el.html(this.template({title: 'Title'}));
this.$events = this.$('.js-events');
_.each(this._EventViews, function (eventView) {
this.$events.append(eventView.render().$el);
}, this);
return this;
}
The render() function shouldn't be responsible for handling the setup of the view.el. This is done by Backbone in the _ensureElement function that is called when you initialize the view.
Also, the $.fn.html() function is only supposed to return the contents of the selected element.
You have many options but I think the most flexible and sustainable approach is to get each sub view to define its own template. The parent view simply appends the child elements .el property.
The advantages of this approach, your template is only compiled once. And updates to children do not require re-rendering parent and neighbouring elements.
Here is a JSBin
Example:
var ContainerView = Backbone.View.extend({
tagName: "article",
className: "event",
id: "someID342",
initialize: function(options){
//the template will now be rendered
this.childView = new ChildView()
//the rendered child will now appear within the parent view
this.el.appendChild( this.childView.el )
}
})
var ChildView = Backbone.View.extend({
tagName: "h1",
dateString:"01/02/2010",
prefix: "Date: ",
caption: "What a wonderful date!:",
title: "I am a title",
template: _.template([
'<h1>',
'<span class="date"><%= prefix %><%= dateString %></span>',
'<span class="title"><%= title %></span>',
'</h1>',
'<div class="caption"><%= caption %></div>'
].join("")),
initialize: function(){
this.render()
},
render: function(){
// because you are only altering innerHTML
// you do not need to reappend the child in the parent view
this.el.innerHTML = this.template(this)
}
})
I'd personally caution against using templates in Backbone at all. I've found that simply having a Backbone view for every component of your app becomes a lot easier to edit later. Sharing templates is a lot harder than sharing views. Of course it depends on the requirements of your project.

Ember Transition with query param

I'm creating an ember.js app. The first page is single field, with a button. On button click, I'd like it to go to the path #/deals/:api_key. However, when I click the button, I'm not clear on the best way to go about it.
Here's what i have so far:
App = Ember.Application.create();
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.FixtureAdapter'
});
App.Deal = DS.Model.extend({
name: DS.attr('string')
});
App.Router.map(function() {
this.resource('start', { path: '/' });
this.resource('deals', { path: '/deals/:api_key' });
});
App.DealsRoute = Ember.Route.extend({
model: function(params) {
return App.Deal.find();
}
});
App.StartController = Ember.ObjectController.extend({
apiKey: "",
getDeals: function (model) {
this.transitionToRoute('deals');
}
});
App.DealsView = Ember.View.extend({
didInsertElement: function() {
// Add active class to first item
this.$().find('.item').first().addClass('active');
this.$().find('.carousel').carousel({interval: 1000});
}
});
<script type="text/x-handlebars" data-template-name="start">
{{view Em.TextField valueBinding="apiKey" placeholder="API Key"}}
<br />
<button {{action 'getDeals'}} class="btn btn-large">Get Won Deals!</button>
</script>
<script type="text/x-handlebars" data-template-name="deals">
<div id="carousel" class="carousel slide">
<div class="carousel-inner">
{{#each model}}
<div class="item">
{{name}}
</div>
{{/each}}
</div>
</div>
</script>
Any suggestions on the right way to pass data from a text input into the next transition as a query param?
you need to pass the parameter in the view in a linkTo helper, e.g.
{{#linkTo 'deals' api_key}}go to deals{{/linkTo}}
this generates a link with the dynamic section you need.
go to deals
check the docs about linkTo for more info: http://emberjs.com/guides/templates/links/

Categories

Resources