Loading a single model with Ember.js - javascript

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.

Related

How to create an array of previously retrieved posts from an AJAX request

Here is the problem I am working on.
Attached is an index.html.
Implement the next and previous buttons to navigate to next/previous posts from the API provider (https://jsonplaceholder.typicode.com).
Create a new tag that displays the current post ID.
Bonus points: Create a new array to store all of the previously retrieved posts, and display them in a list.
The API is from jsonplaceholder.typicode.com, so you don't need to implement that. A jsfiddle would be immensely appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Vue Test</title>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<div id="app">
<h1>{{ message }}</h1>
<div>
<span>{{post.title}}</span>
</div>
<button v-on:click="previousPost">Previous Post</button> <!-- // new vue directive - v-on:click, also -->
<button v-on:click="nextPost">Next Post</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
***emphasized text***crossorigin="anonymous"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Welcome to Vue!',
post: {},
page: 1
},
mounted: function() {
this.getPost()
},
methods: {
nextPost: function() {
this.page = this.page + 1
this.getPost()
// Implement me
},
previousPost: function() {
// Implement me
this.page = this.page - 1
this.getPost()
},
getPost: function() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/' + this.page,
method: 'GET'
})
.then((data) => {
console.log(data);
this.post = data;
});
}
}
})
</script>
<style>
/* Add any additional styles here */
body {
padding: 20px;
}
div {
margin: 12px 0;
}
</style>
I would also like to know what is meant by the post id over there. I have completed one task which shows the next and previous posts, but the other two tasks I am a little confused.

Access an element when the "Submit" button is clicked to get the values

So here's a great example from https://developer.forecast.io/docs/v2
What I want to do and trying is this:
I have a simply webpage whereby I want to display the current forecast and extended forecast.
Here's my Index.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html lang="en" class="no-js" ng-app="myApp">
<head>
<title>Weather Forecaster</title>
<meta charset="UTF-8">
<!-- favicon -->
<link rel="shortcut icon" href="images/Oxygen-Icons.org-Oxygen-Status-weather-clear.ico" />
<!-- END favicon -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="css/jquery.jdigiclock.css" rel="stylesheet" type="text/css" />
<link href="css/wx-custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery-1.12.2.js"></script>
</head>
<body ng-controller="wxController as ctrlWx">
<div class="container">
<div class="row">
<div class="col-10">
<div id="my-div" ng-model="myiFrame">
<iframe src="http://www.latlong.net/convert-address-to-lat-long.html" id="my-iframe" scrolling="no"></iframe>
</div>
<div id="plugin_container" class="forecast-panel">
<h1>Here's Today's Weather</h1>
<div class="fc forecast-panel1">
<p class="dayTitle">Day 1</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel2">
<p class="dayTitle">Day 2</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel3">
<p class="dayTitle">Day 3</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel4">
<p class="dayTitle">Day 4</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel5">
<p class="dayTitle">Day 5</p>
</div>
</div>
</div>
</div>
</div>
<script src="js/angular/angular.min.js" type="text/javascript"></script>
<script src="js/angular/app.js" type="text/javascript"></script>
<script src="js/angular/controller.js" type="text/javascript"></script>
<script src="js/angular/services.js" type="text/javascript"></script>
<script src="js/angular/ang-custom.js" type="text/javascript"></script>
</body>
</html>
Notice the "IFRAME".... the src is this: http://www.latlong.net/convert-address-to-lat-long.html
Now, if you go there, which is pretty cool, you can put ANY address to get the LAT LON for that address:
Here's a screen shot with an example LAT LON from DC... the Whitehouse.
OK, now, my code uses Angular with a simple controller and service...
Here:
APP:
/* global angular */
// Code goes here
var myApp;
myApp = angular.module("myApp", []);
myApp.config(function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', '**']);
});
console.log("Host name is: " + document.location.hostname);
//if (document.location.hostname === "localhost") {
// myApp.constant('URL', '/WeatherForecaster/js/json/');
//} else if (document.location.hostname === "omnimanger.co/wx" || "www.omnimanager.co/wx") {
// myApp.constant('URL', '/js/json/');
//} else {
// myApp.constant('URL', '/wx/js/json/');
//}
myApp.constant("URL", {
//Default LAT/LON for CONCRETE
apiKey: "3bb0f0fe93c92922f0b42f9eabda48d0/",
lat: "48.530031",
lon: ",-121.879460",
country: "us",
uri: "https://api.forecast.io/forecast/"
}).config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});;
myApp.constant("wx", {
data: {
latitude: 0,
longitude: 0,
currently: {},
minutely: {
summary: "",
icon: "",
data: []
},
hourly: {
summary: "",
icon: "",
data: []
},
daily: {
summary: "",
icon: "",
data: []
},
flags: {
sources: [],
"lamp-stations": [],
"isd-stations": [],
"madis-stations": [],
units: ""
}
}
});
CONTROLLER:
'use strict';
myApp.controller('wxController', function (wxDataService) {
var ctrlWx = this;
//Listen for the Submit (FIND) button on the iFrame
ctrlWx.content = {};
console.log("LAT/LON: ", ctrlWx.latlon);
ctrlWx.fetchWx = function () {
//General Data
wxDataService.getWxData().then(function (result) {
ctrlWx.content = result;
console.log("All Data: ", result);
});
};
ctrlWx.fetchWx();
});
SERVICE:
myApp.factory('wxDataService', function ($http, URL) {
console.log("URL", URL);
//DEFAULT Headers for KEY and AUTH TOKEN
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': ['GET', 'POST'],
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json'
};
var myURL = {
data: {
header: headers,
uri: URL.uri + URL.apiKey + URL.lat + URL.lon
}
};
var getWxData = function () {
return $http.get(myURL)
.success(function (data) {
console.log("SUCCESS!");
console.log("The Weather Data is here: " + data);
return data;
})
.error(function (e) {
console.log("He\'s dead Jim!<br>", e);
return e;
});
};
return {
getWxData: getWxData
};
});
SOLUTION I'm Trying to Achieve:
When the user enters the address and clicks the "FIND" button, which generates the LAT LON, I want to capture that LAT LON inside the IFRAME.
This is what I'm trying to do, but I know I need to make a directive that BINDS the "CLICK" or "SUBMIT" event to the FIND button. What I have below is NOT that; yet.
var latlon = {};
$(function () {
$('#my-iframe').load(function () {
$(this).contents().find("#latlongform, #gadres").live('blur', function (e) {
latlon = {
mylat: $("input[name='lat']").val(),
mylon: $("input[name='lon']").val()
};
if (e) {
console.log("Err: ", e);
return e;
}
});
});
});
GIVENS:
The FORM and the LAT LON are as follows:
<div class="row">
<div class="col-8 graybox">
<form id="latlongform">
<label for="gadres">Address</label>
<input id="gadres" type="text" class="width70" placeholder="Type address here to get lat long" required="">
<button title="Find lat long coordinates" class="button">Find</button><br>
<small>Write city name with country code for better results.</small>
</form>
<div class="row">
<div class="col-6 m2">
<label for="lat">Latitude</label>
<input type="text" name="lat" id="lat" placeholder="lat coordinate">
</div>
<div class="col-6 m2">
<label for="lng">Longitude</label>
<input type="text" name="lng" id="lng" placeholder="long coordinate">
</div>
</div>
</div>
</div>
QUESTION:
How can I get the LAT LON, "AFTER" the user clicks FIND, THEN fire my angular service to inject the CALL to the URL which gets the WEATHER DATA...as described. Here's that WEATHER DATA JSON OBJECT. It uses an API KEY which mine is limited to 1000 uses per day.
If you'd like to see what the result is on the weather API, you need to get a FREE API_KEY.... it gives 1000 hits per day...
Thanks everyone and I hope you can all this this is a VALID question.
Accessing the Forecast.io API with JSONP
The forecast.io website doesn't support CORS (Cross Origin Resource Sharing) for GET operations but it does support JSONP.
Revised Code
var url = myURL.data.uri;
var jsonpURL = url+"?callback=JSON_CALLBACK";
var getWxData = function () {
return $http.jsonp(jsonpURL)
.then(function (response) {
console.log("SUCCESS!");
console.log(response.data);
//return to chain data
return response.data;
})
.catch(function (e) {
console.log("He\'s dead Jim!");
console.log(e);
//throw to chain rejection
throw e;
});
};
Sample Result
LAT: 48.530031
LOG: -121.87946
TIMEZONE: America/Los_Angeles
SUMMARY: Partly Cloudy
TEMP: 56.02
The DEMO on JSFiddle.
Notice that I changed the .success and .error methods to .then and .catch respectively. Those old methods are deprecated and ignore return values.

Routing and button click not working in Backbone + handlebars

index.html
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="js/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="js/lib/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
<link href="js/lib/ratchet/ratchet-theme-ios.css" rel="stylesheet">
<link href="js/lib/ratchet/ratchet.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>totter</title>
</head>
<body>
<div class="content">
</div>
<script src="js/lib/jquery-1.9.1.min.js"></script>
<script src="js/lib/underscore-min.js"></script>
<script src="js/lib/backbone-min.js"></script>
<script src="js/lib/bootstrap/js/bootstrap.js"></script>
<script src="js/lib/handlebars/handlebars-v1.3.0.js"></script>
<script src="js/lib/ratchet/ratchet.js"></script>
<script src="js/common/helper.js"></script>
<script src="js/app.js"></script>
<script src="js/views/home.js"></script>
<script src="js/views/signin.js"></script>
<script src="js/models/home.js"></script>
<script src="js/models/signin.js"></script>
</body>
</html>
app.js
var app = {
views: {},
models: {},
loadTemplates: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (app[view]) {
deferreds.push($.get('template/' + view + '.hbs', function(data) {
app[view].prototype.template = _.template(data);
}, 'html'));
} else {
alert(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}
};
app.Router = Backbone.Router.extend({
routes: {
"": "home",
"signIn":"SignIn"
},
home: function () {
// Since the home view never changes, we instantiate it and render it only once
if (!app.home) {
app.home = new app.HomeView();
app.home.render();
} else {
// delegate events when the view is recycled
app.home.delegateEvents();
}
},
SignIn:function(){
if (!app.signin) {
app.signin = new app.SignInView();
app.signIn.render();
} else {
// delegate events when the view is recycled
app.signin.delegateEvents();
}
}
});
$(document).on("ready", function () {
app.loadTemplates(["HomeView"],
function () {
app.router = new app.Router();
Backbone.history.start();
});
});
home.js
app.HomeView = Backbone.View.extend({
//Calling the render method to render view from the template
initialize:function(){
this.render();
},
//Pass the handlebars template for complilation and
render: function () {
var path = './template/HomeView.hbs';
Helper.GET_TEMPLATE(path, function(template) {
//pass collection to template to set values
var html = template(app.homeCollection.toJSON());
//pass collection to template to set values
$('.content').html(html);
});
$('.signin').bind('click', function(e) {
app.Router.navigate("signIn", {trigger: true});
});
}
});
app.home = new app.HomeView();
sigin.js
app.SigInView = Backbone.View.extend({
//Calling the render method to render view from the template
initialize:function(){
this.render();
},
//Pass the handlebars template for complilation and
render: function () {
var path = './template/SignInView.hbs';
Helper.GET_TEMPLATE(path, function(template) {
//pass collection to template to set values
var html = template(app.signinCollection.toJSON());
//pass collection to template to set values
$('.content').html(html);
});
}
});
app.signin = new app.SigInView();
helper.js
var Helper = {};
Helper.GET_TEMPLATE = function(path,callback){
var source, template;
$.ajax({
url: path,
success: function(data) {
source = data;
//Compile the raw data we got from the file
template = Handlebars.compile(source);
//execute the callback if passed
if (callback){
callback(template);
}
}
});
}
homeModel.js
var HomeModel = Backbone.Model.extend();
var homeData = new HomeModel({
id: 1,
signUpTitle: 'Sign Up for TOT ',
signInTitle: 'Sign In',
slogan:'slogan slogan slogan slogan slogan slogan slogan slogan slogan slogan '
});
/**
* Defining a Collection to set model
*/
var HomeCollection = Backbone.Collection.extend({
model: HomeModel
});
/**
* Defining a array to hold the collection
*/
app.homeCollection = new HomeCollection([homeData]);
HomeView.hbs
<header class="bar bar-nav">
<h1 class="title">totter</h1>
</header>
<div class="logo">
<img src = "img/choice.png">
</div>
{{#each []}}
<div class="textcontent">
<label>{{this.slogan}}</label>
</div>
<div class="footer">
<button class="btn btn-primary btn-block signup" style="">{{this.signUpTitle}}</button>
</div>
<div class="footer">
<button class="btn btn-primary btn-block signin">{{this.signInTitle}}</button>
</div>
{{/each}}
In the above code I used to develop a simple app with 2 views. I want to show sign-in view on button click of sign-in.
How can I achive this? I am using "handlebars" and "backbone.js".
The events aren't firing because you're utilizing the View el property. Either give it a preexisting element or insert the el itself to the DOM.
see the answer on the following discussion for a more comprehensive explanation.

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

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