Ember handling multiple returns? - javascript

I have two json inputs,
Input 1 :
var status = [{
isLogged : true
}];
Input2 :
var posts = [{
id: '1',
datalink:124,
isVoted : true,
votecount : 123,
title: "Rails is Omakase",
author: { name: "d2h" },
date: new Date('12-27-2012'),
excerpt: "There are lots of à la carte software environments in this world. Places where in order to eat, you must first carefully look over the menu of options to order exactly what you want."
}]
Everything worked fine when there was one json,
App.Route = Ember.Route.extend({
model : function(){
return posts;
}
});
But when I added the second input it doesn't work
App.Route = Ember.Route.extend({
model : function(){
return posts;
},
logged : function(){
return status;
}
});
How can I get the second input and disply in the html?
{{#if isLogged}}
<li>Logout</li>
{{else}}
<li>Login</li>
{{/if}}

You need to add the second input into your Route's controller.
App.Route = Ember.Route.extend({
model : function(){
return posts;
},
setupController(controller, model){
controller.set("model", model);
controller.set("isLogged", status);
}
});
And since the isLogged will be declared in the controller, it should be visible within the view.

Related

Model doesn't change when modify view elements in backbone.js

I am validating model's attribute (Name), in order to make sure, customer have to input their name in the register form.
View :
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/CustomerTemplate.html",
"models/Customer"
],function($ , _ , Backbone, CustomerTemplate, CustomerModel){
var CustomerView = Backbone.View.extend({
initialize : function(){
this.listenTo(this.model, 'change', this.render);
},
events : {
'submit #customerForm' : 'Customer'
},
Customer : function(e){
e.preventDefault()
var _customer = new CustomerModel({
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: $("#name").val(),
});
this.model.save(_customer,{validate: true},{
wait:true,
success:function(model, response) {
console.log('Successfully saved!');
},
error: function(model, error) {
console.log(model.toJSON());
console.log('error.responseText');
}
});
},
render : function(){
var customertemplate = _.template(CustomerTemplate);
this.$el.html(customertemplate(this.model.toJSON()));
return this;
}
});
return CustomerView;
});
Model:
define(["underscore" , "backbone"],function(_ , Backbone){
var CustomerModel = Backbone.Model.extend({
urlRoot: "myurl",
initialize : function(){
this.bind('invalid', function(model, error) {
console.log(error);
});
},
validate: function (attrs){
if ( !attrs.Name) {
return 'You must provide a name';
}
},
defaults : {
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: "",
}
});
return CustomerModel;
});
Problem : Even the attribute Name is not null, the error message in validate method still appears (You must provide a name).
Any idea what could be causing this is appreciate. Thanks.
When you call this.model.save in your CustomerView, you're passing it a new Customer model you instantiated in the previous statement. This isn't quite what you want; you either want to call _customer.save() to save the brand new model, or - more likely - you want to pass your new attributes to the existing model, and save that:
var newAttrs = {
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: $("#name").val(),
};
this.model.save(newAttrs);
When you call this.model.save(_customer, {validate: true}) in your existing code, that Customer model get passed to your validate() function. And that model doesn't have a Name attribute. It does have a Name property - you can access it via _customer.get('Name') - but you should follow the Backbone convention and presume that your validate method is getting a 'simple' JavaScript object, not a Backbone model.

Refresh view on Ember Data update

I’m doing a very basic application with Ember and Ember Data.
For some reason I always have the same problem. My application renders and displays the data correctly, but if I remove and search, it doesn't update the view.
I’ve already asked this here—the link has more code examples—but with not much luck. Here is how I’m trying to do it:
App = Ember.Application.create({
LOG_TRANSITIONS: true, LOG_VIEW_LOOKUPS: true
});
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Sample = DS.Model.extend({ name: DS.attr('string') });
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('sample');
}
});
App.IndexController = Ember.ArrayController.extend({
actions: {
remove: function(sample) {
sample.destroyRecord();
}
}
});
App.Sample.FIXTURES = [
{ id: 1, name: 'Learn Ember.js'},
{ id: 2, name: 'Record 2' },
{ id: 3, name: 'Test Delete' }
];
App.ApplicationRoute = Ember.Route.extend({
actions: {
showModal: function(name, content) {
this.controllerFor(name).set('content', content);
this.render(name, {
into: 'application',
outlet: 'modal'
});
},
removeModal: function() {
this.disconnectOutlet({
outlet: 'modal',
parentView: 'application'
});
}
}
});
App.MyModalComponent = Ember.Component.extend({
actions: {
ok: function() {
this.$('.modal').modal('hide');
this.sendAction('ok');
}
},
show: function() {
this.$('.modal').modal().on('hidden.bs.modal', function() {
this.sendAction('close');
}.bind(this));
}.on('didInsertElement')
});
From your code I have tried to come up with a reasonable solution for your problem
Before I get into the solution I think the controller should be IndexController rather than sampleDeleteModalController because ember expects controller to have same name as the route.
App.SampleDeleteModalController = Ember.ObjectController.extend({
actions: {
remove: function() {
// Two ways
this.get('model').destroyRecord();
this.transitionToRoute('index');
}
}
});
transitionToRoute from the same route will not refresh a view.This will work only when you want to redirect to another route.
Solution to refresh view
option 1 : you can capture the same action inside index route after removing the record you can do this.refesh() which refreshes the model.
option 2 : You have to explicitly update the binded model inside the controller.
actions: {
remove: function() {
// Two ways
var localCopy = this.get('model');
localCopy.destroyRecord();
this.set('model',localCopy);
}
}
option 3 : After you set your model your model and then do this.rerender().Which is almost equivalent to window.reload()

Handlebars won't loop over my Backbone.js Collection

I have a Backbone app where I'm attempting to populate a collection using a JSON file. I want to generate a list of "titles" from the JSON to eventually turn into a menu.
Everything is going well, except that Handlebars won't loop (each) over my collection to render the list.
The relevant view:
var MenuView = Backbone.View.extend({
template: Handlebars.compile(
'<ul>' +
'{{#each items.models}}<li>{{attributes.title}}</li>{{/each}}' +
'</ul>'
),
initialize: function () {
this.listenTo(this.collection, "reset", this.render);
},
render: function () {
this.$el.html(this.template(items));
return this;
}
});
The model and collection:
var Magazine = Backbone.Model.extend({
urlRoot:"/items",
defaults: {
id: '',
title: '',
pubDate: '1/1',
image: ''
}
});
var MagazineMenu= Backbone.Collection.extend({
comparator: 'title',
model: Magazine,
url: "/items"
});
The router:
var MagazineRouter = Backbone.Router.extend({
routes: {
"" : "listPage",
"titles/:id" : "showTitle"
},
initialize: function () {
this.magazineModel = new Magazine();
this.magazineModel.fetch();
this.magazineView = new MagazineView({
model: this.magazineModel
});
this.magazineCollection = new MagazineMenu();
this.magazineCollection.fetch();
this.menuView = new MenuView({collection: this.magazineCollection});
},
showTitle: function(id) {
this.magazineModel.set("id", id);
$("#theList").html(this.magazineView.render().el);
},
listPage : function() {
$('#theList').html(this.menuView.render().el);
}
});
var router = new MagazineRouter();
$(document).ready(function() {
Backbone.history.start();
});
And finally the JSON:
[
{
"id": "screamingzebras",
"url": "screamingzebras",
"title": "Screaming Zebras",
"pubDate": "2/1",
"image": "screamingzebras.jpg"
},
{
"id": "carousellovers",
"url": "carousellovers",
"title": "Carousel Lovers",
"pubDate": "3/1",
"image": "carousellovers.jpg"
},
{
"id": "gardenstatuary",
"url": "gardenstatuary",
"title": "Garden Statuary",
"pubDate": "4/1",
"image": "gardenstatuary.jpg"
},
{
"id": "sombreromonthly",
"url": "sombreromonthly",
"title": "Sombrero Monthly",
"pubDate": "1/1",
"image": "sombreromonthly.jpg"
}
]
When I run this in a browser, I get no errors in the console. If I console.log(this.collection) just before the call to this.$el.html(this.template(items)); in the view, I can see the collection with a models attribute that is properly populated from the JSON.
When I look at the Elements panel in Chrome dev tools, I can see that it is generating everything up to and including the <ul> tag. That leads me to believe that I'm just missing a key logic point that is getting the Handlebars each function to actually loop over the collection.
I see two problems here:
items isn't defined anywhere so your render is really saying this.template(undefined).
Even if you did have a local variable called items, your Handlebars template won't know that you've called it items so it won't know that {{#each items.models}} should iterator over it.
Presumably your items is really supposed to be the view's this.collection and your render should look more like this:
render: function () {
this.$el.html(this.template(this.collection));
return this;
}
That should solve problem 1. You can fix problem 2 in two ways:
Change the template to refer to the right thing.
Change how you call this.template so that items is associated with the right thing.
The first option would use the above render and a template that looks like this:
<ul>
{{#each models}}
<li>{{attributes.title}}</li>
{{/each}}
</ul>
The second option would leave your template alone but change render to use:
this.$el.html(
this.template({
items: this.collection
})
);
Another option would be to use this.collection.toJSON() to supply data to the template, then render would use:
this.$el.html(
this.template({
items: this.collection.toJSON()
})
);
and then template would be:
<ul>
{{#each items}}
<li>{{title}}</li>
{{/each}}
</ul>

Ember.js: Computed property on current element in array

So, this is what my model looks like (represented by fixture data):
var posts = [{
id: 'b026324c6904b2a9',
title: "My new front door",
author: { name: "Matthieu" },
date: new Date('2013-10-28T12:19:30.789'),
status: 'new',
hidden_message: "hidden1"
}, {
id: '26ab0db90d72e28a',
title: "Best pizza in town",
author: { name: "Harry" },
date: new Date('2013-10-28T12:19:30.789'),
status: '',
hidden_message: "hidden2"
}, {
id: '6d7fce9fee471194',
title: "Skateboard dreamland",
author: { name: "Matthieu" },
date: new Date('2013-10-28T12:19:30.789'),
status: 'solved',
hidden_message: "hidden3"
}, {
id: '48a24b70a0b37653',
title: "my house looks like a pumpkin",
author: { name: "Harry" },
date: new Date('2013-10-28T12:19:30.789'),
status: '',
hidden_message: "hidden4"
}];
My route:
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts;
}
});
And, I'd like to be able to display a certain piece of HTML in the template if the corresponding post is new, a different one if it's solved, and nothing if the status is blank. It seems to me as if the best way to do this is using an {{#if}} helper, but that doesn't do equality comparisons, it can only take a boolean variable. So, I'd like to do something like this:
App.IndexController = Ember.ArrayController.extend({
isNew: function(val) {
if(this.get('currentitem.status') === 'new') {
return true;
}
return false;
}.property('isNew')
});
But I can't find out how to select the item being currently accessed by {{#each}} in the template. Is this even possible, and if yes, how do I do it (or something similar)?
Thanks all!
The correct way to do this is to create an itemcontroller that helps you by providing a controller per item in your collection.
App.IndexController = Ember.ArrayController.extend({
itemController: "PostItem",
});
App.PostItemController = Ember.ObjectController.extend({
isNew: function() {
if(this.get('status') === 'new') {
return true;
}
return false;
}.property('status')
});
Then in your handlebar template you can just call {{isNew}} in the {{#each}}-context.
I've put up a working fiddle that you can test it out in.
http://jsfiddle.net/LordDaimos/v8NR3/1/
Best way would probably be to wrap each post in an object that has the isNew method, like this:
var postObject = Ember.Object.extend({
isNew: function() {
if(this.get('status') === 'new') {
return true;
}
return false;
}.property('status')
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts.map(function(post){
return postObject.create(post);
});
}
});
this way you could query on each post.

Backbone.js routing depending on model value

I have a collection that looks something like this
[
{
"year": 1868,
....
]
},
{
"year": 1872,
....
},
{
...
}
]
Is there a way to set a route either with '/year/:year': 'year' or '/(:year)': 'year' ?
I have tried making a lookup table in the main App view, which passes the year index to the model views. I have tried using _.map, _.each, _.pluck and _.where but I guess I must be doing something wrong.
Here is a non Backbone view of what it looks like. So navigating to /(:year) would go straight to that year, which corresponds to an model index
Edit: to clarify, basically I want the user to be able to go to /year/:year, but :year value corresponds to a certain model (see above). In this case going to /year/1868, would render the first model from the above collection.
EDIT #2: Here is how my app looks like.
this is the router
var router = Backbone.Router.extend({
routes: {
'': 'root',
'year(/:year)': 'year'
},
root: function() {
new App();
},
year: function(year) {
new App({
year: year
});
}
});
which calls this file
define(['backbone', 'assets/js/collections/elections.js', 'assets/js/views/election.js', 'jqueryui'], function(Backbone, Elections, ElectionView, simpleSlider) {
var AppView = Backbone.View.extend({
current_election_index: 0,
active_btn_class: 'dark_blue_bg',
wiki_base: 'http://en.wikipedia.org/wiki/United_States_presidential_election,_',
started: 0,
el: 'body',
playback: {
id: '',
duration: 1750,
status: false
},
initialize: function() {
elections = new Elections();
_.bindAll(this, 'render');
this.listenTo(elections, 'reset', this.render);
elections.fetch();
this.remove_loader();
},
render: function () {
if (this.started === 0) {
this.election_year();
}
var view = new ElectionView({
model: elections.at(this.current_election_index),
election_index: this.current_election_index
});
this._make_slider();
this.update_ui();
return this;
},
I took out some of the methods, since they are non essential.
A typical solution would looks something like this:
var AppRouter = Backbone.Router.extend({
routes: {
"year(/:year)" : "electionByYear"
},
electionByYear: function(year) {
//all of your data, wherever you get it from
var results = this.allElectionResults;
//if a year parameter was given in the url
if(year) {
//filter the data to records where the year matches the parameter
results = _.findWhere(results, { year: parseInt(year, 10)});
}
doSomething(results);
}
});
Edit based on comments: If your view is responsible for creating the collection, you should move the above logic to your view, and simply pass the year parameter to your view as an argument:
var View = Backbone.View.extend({
initialize: function(options) {
this.year = options.year;
}
});
var view = new View({year:year});
view.render();
Or if you're using an existing view:
view.year = year;
view.render();

Categories

Resources