How to use hogan templates with backbone code?How to combine the values of a model into the Hogan templates?
My HTML page:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Backbone.js • TodoMVC</title>
<link rel="stylesheet" href="js/assets/base.css">
</head>
<body>
<section id="todoapp">
<header id="header">
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
</header>
<section id="main">
<input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list"></ul>
</section>
<footer id="footer"></footer>
</section>
<div id="info">
<p>Double-click to edit a todo</p>
<p>Written by Addy Osmani</p>
<p>Part of TodoMVC</p>
</div>
<script type="text/template" id="item-template">
<div class="view">
<input class="toggle" type="checkbox" {{ completed ? 'checked' : '' }}>
<label>{{ title }}</label>
<button class="destroy"></button>
</div>
<input class="edit" value="{{ title }}">
</script>
<script type="text/template" id="stats-template">
<span id="todo-count"><strong>{{ remaining }}</strong> {{ remaining === 1 ? 'item' : 'items' }} left</span>
<ul id="filters">
<li>
<a class="selected" href="#/">All</a>
</li>
<li>
Active
</li>
<li>
Completed
</li>
</ul>
{[ if (completed) { ]}
<button id="clear-completed">Clear completed ({{ completed }})</button>
{[ } ]}
</script>
<script src="js/assets/base.js"></script>
<script src="js/lib/jquery.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<script src="js/lib/backbone.localStorage.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/collections/todos.js"></script>
<script src="js/views/todos.js"></script>
<script src="js/views/app.js"></script>
<script src="js/routers/router.js"></script>
<script src="js/app.js"></script>
</body>
</html>
My js code
/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};
(function ($) {
'use strict';
_.templateSettings = {
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
};
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
app.AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: '#todoapp',
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
'keypress #new-todo': 'createOnEnter',
'click #clear-completed': 'clearCompleted',
'click #toggle-all': 'toggleAllComplete'
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function () {
this.allCheckbox = this.$('#toggle-all')[0];
this.$input = this.$('#new-todo');
this.$footer = this.$('#footer');
this.$main = this.$('#main');
this.$list = $('#todo-list');
this.listenTo(app.todos, 'add', this.addOne);
this.listenTo(app.todos, 'reset', this.addAll);
this.listenTo(app.todos, 'change:completed', this.filterOne);
this.listenTo(app.todos, 'filter', this.filterAll);
this.listenTo(app.todos, 'all', this.render);
// Suppresses 'add' events with {reset: true} and prevents the app view
// from being re-rendered for every model. Only renders when the 'reset'
// event is triggered at the end of the fetch.
app.todos.fetch({reset: true});
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function () {
var completed = app.todos.completed().length;
var remaining = app.todos.remaining().length;
if (app.todos.length) {
this.$main.show();
this.$footer.show();
this.$footer.html(this.statsTemplate({
completed: completed,
remaining: remaining
}));
this.$('#filters li a')
.removeClass('selected')
.filter('[href="#/' + (app.TodoFilter || '') + '"]')
.addClass('selected');
} else {
this.$main.hide();
this.$footer.hide();
}
this.allCheckbox.checked = !remaining;
},
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function (todo) {
var view = new app.TodoView({ model: todo });
this.$list.append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function () {
this.$list.html('');
app.todos.each(this.addOne, this);
},
filterOne: function (todo) {
todo.trigger('visible');
},
filterAll: function () {
app.todos.each(this.filterOne, this);
},
// Generate the attributes for a new Todo item.
newAttributes: function () {
return {
title: this.$input.val().trim(),
order: app.todos.nextOrder(),
completed: false
};
},
// If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function (e) {
if (e.which !== ENTER_KEY || !this.$input.val().trim()) {
return;
}
app.todos.create(this.newAttributes());
this.$input.val('');
},
// Clear all completed todo items, destroying their models.
clearCompleted: function () {
_.invoke(app.todos.completed(), 'destroy');
return false;
},
toggleAllComplete: function () {
var completed = this.allCheckbox.checked;
app.todos.each(function (todo) {
todo.save({
'completed': completed
});
});
}
});
})(jQuery);
it is from the ToDo example. I used Mustache templates here by changing the template settings. But i want to convert the template into Hogan.
my Edited js:
/*global Backbone, jQuery, _, ENTER_KEY, ESC_KEY */
var app = app || {};
(function ($) {
'use strict';
// Todo Item View
// --------------
_.templateSettings = {
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
};
// The DOM element for a todo item...
app.TodoView = Backbone.View.extend({
tagName: 'li',
// Cache the template function for a single item.
template1: _.template($('#item-template').html()),
template:Hogan.compile(template1),
// The DOM events specific to an item.
events: {
'click .toggle': 'toggleCompleted',
'dblclick label': 'edit',
'click .destroy': 'clear',
'keypress .edit': 'updateOnEnter',
'keydown .edit': 'revertOnEscape',
'blur .edit': 'close'
},
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
this.listenTo(this.model, 'visible', this.toggleVisible);
},
render: function () {
// Backbone LocalStorage is adding `id` attribute instantly after creating a model.
// This causes our TodoView to render twice. Once after creating a model and once on `id` change.
// We want to filter out the second redundant render, which is caused by this `id` change.
// It's known Backbone LocalStorage bug, therefore we've to create a workaround.
// https://github.com/tastejs/todomvc/issues/469
if (this.model.changed.id !== undefined) {
return;
}
console.log(this.template);
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('completed', this.model.get('completed'));
this.toggleVisible();
this.$input = this.$('.edit');
return this;
},
toggleVisible: function () {
this.$el.toggleClass('hidden', this.isHidden());
},
isHidden: function () {
var isCompleted = this.model.get('completed');
return (// hidden cases only
(!isCompleted && app.TodoFilter === 'completed') ||
(isCompleted && app.TodoFilter === 'active')
);
},
toggleCompleted: function () {
this.model.toggle();
},
edit: function () {
this.$el.addClass('editing');
this.$input.focus();
},
close: function () {
var value = this.$input.val();
var trimmedValue = value.trim();
if (!this.$el.hasClass('editing')) {
return;
}
if (trimmedValue) {
this.model.save({ title: trimmedValue });
if (value !== trimmedValue) {
this.model.trigger('change');
}
} else {
this.clear();
}
this.$el.removeClass('editing');
},
updateOnEnter: function (e) {
if (e.which === ENTER_KEY) {
this.close();
}
},
revertOnEscape: function (e) {
if (e.which === ESC_KEY) {
this.$el.removeClass('editing');
}
},
clear: function () {
this.model.destroy();
}
});
})(jQuery);
Related
I am struggling with displaying two models/collections in the same page.
<body>
<div id="mainContainer">
<div id="contentContainer"></div>
</div>
<div id="mainContainer2">
<div id="contentContainer2"></div>
</div>
<script id="list_container_tpl" type="text/template">
<div class="grid_5 listContainer">
<div class="box">
<h2 class="box_head grad_colour">Your tasks</h2>
<div class="sorting">Show: <select id="taskSorting"><option value="0">All Current</option><option value="1">Completed</option></select>
<input class="search round_all" id="searchTask" type="text" value="">
</div>
<div class="block">
<ul id="taskList" class="list"></ul>
</div>
</div>
</div>
</script>
<script id="list2_container_tpl" type="text/template">
<div class="grid_5 mylistContainer">
<div class="box">
<h2 class="box_head grad_colour">Your facets</h2>
<div class="sorting">
%{--Show: <select id="taskSorting"><option value="0">All Current</option><option value="1">Completed</option></select>--}%
<input class="search round_all" id="searchFacet" type="text" value="">
</div>
<div class="block">
<ul id="facetList" class="list"></ul>
</div>
</div>
</div>
</script>
<script id="task_item_tpl" type="text/template">
<li class="task">
<h4 class="name searchItem">{{ name }}</h4>
</li>
</script>
<script id="facet_item_tpl" type="text/template">
<li class="facet">
<h5 class="label searchItem">{{ label }}</h5>
</li>
</script>
<script>
var myapp = {
model: {},
view: {},
collection: {},
router: {}
};
var facetsSearch = {
model: {},
view: {},
collection: {},
router: {}
};
</script>
<script src="underscore-min.js"></script>
<script src="handlebars.min.js"></script>
<script src="backbone-min.js"></script>
<script>
/* avoid */
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
</script>
<script>
// model.tasks.js
myapp.model.Tasks = Backbone.Model.extend({
default:{
completed: 0,
name: ""
},
//url:"/js/libs/fixtures/task.json"
});
var tasks1 = new myapp.model.Tasks({
completed: 0,
name: "Clear dishes"
}
);
var tasks2 = new myapp.model.Tasks({
completed: 1,
name: "Get out the trash"
}
);
var tasks3 = new myapp.model.Tasks({
completed: 0,
name: "Do the laundry"
}
);
var tasks4 = new myapp.model.Tasks({
completed: 1,
name: "Vacuuming the carpet"
}
);
// collection.tasks.js
myapp.collection.Tasks = Backbone.Collection.extend({
currentStatus : function(status){
return _(this.filter(function(data) {
return data.get("completed") == status;
}));
},
search : function(letters){
if (letters == "") return this;
var pattern = new RegExp(letters,"gi");
return _(this.filter(function(data) {
return pattern.test(data.get("name"));
}));
}
});
myapp.collection.tasks = new myapp.collection.Tasks([tasks1, tasks2, tasks3, tasks4]);
// route.tasks.js
myapp.router.Tasks = Backbone.Router.extend({
routes: {
"": "list",
},
list: function(){
this.listContainerView = new myapp.view.TasksContainer({
collection: myapp.collection.tasks
});
$("#contentContainer").append(this.listContainerView.render().el);
this.listContainerView.sorts()
}
});
myapp.router.tasks = new myapp.router.Tasks;
<!-- render views -->
myapp.view.TasksContainer = Backbone.View.extend({
events: {
"keyup #searchTask" : "search",
"change #taskSorting" : "sorts"
},
render: function(data) {
$(this.el).html(this.template);
return this;
},
renderList : function(tasks){
$("#taskList").html("");
tasks.each(function(task){
var view = new myapp.view.TasksItem({
model: task,
collection: this.collection
});
$("#taskList").append(view.render().el);
});
return this;
},
initialize : function(){
this.template = _.template($("#list_container_tpl").html());
this.collection.bind("reset", this.render, this);
},
search: function(e){
var letters = $("#searchTask").val();
this.renderList(this.collection.search(letters));
},
sorts: function(e){
var status = $("#taskSorting").find("option:selected").val();
if (status == "") status = 0;
this.renderList(this.collection.currentStatus(status));
}
});
myapp.view.TasksItem = Backbone.View.extend({
events: {},
render: function(data) {
$(this.el).html(this.template(this.model.toJSON()));
console.log(this.model.toJSON(), "became", this.template(this.model.toJSON()));
return this;
},
initialize : function(){
this.template = _.template($("#task_item_tpl").html());
}
});
</script>
<script>
// model.facets.js
facetsSearch.model.Facets = Backbone.Model.extend({
default: {
id: 0,
label: "",
facetValues: []
}
});
var facet1 = new facetsSearch.model.Facets({
id: 1,
label: "Organism",
facetValues: ["Orga1", "Orga2"]
});
var facet2 = new facetsSearch.model.Facets({
id: 2,
label: "Omics",
facetValues: ["Omics1", "Omics2"]
});
var facet3 = new facetsSearch.model.Facets({
id: 3,
label: "Publication Date",
facetValues: ["2016-11-01", "2016-11-02"]
});
// collection.facets.js
facetsSearch.collection.Facets = Backbone.Collection.extend({
search : function(letters){
if (letters == "") return this;
/**
* the g modifier is used to perform a global match (find all matches rather than stopping after the first match).
* Tip: To perform a global, case-insensitive search, use this modifier together with the "i" modifier.
*/
var pattern = new RegExp(letters, "gi");
return _(this.filter(function(data) {
return pattern.test(data.get("label"));
}));
}
});
facetsSearch.collection.facets = new facetsSearch.collection.Facets([facet1, facet2, facet3]);
// route.facets.js
facetsSearch.router.Facets = Backbone.Router.extend({
routes: {
"": "list",
},
list: function(){
this.mylistContainerView = new facetsSearch.view.FacetsContainer({
collection: facetsSearch.collection.facets
});
console.log("Facet collection: ", facetsSearch.collection.facets);
$("#contentContainer2").append(this.mylistContainerView.render().el);
this.mylistContainerView.sorts()
}
});
facetsSearch.router.Facets = new facetsSearch.router.Facets;
facetsSearch.view.FacetsContainer = Backbone.View.extend({
events: {
"keyup #searchFacet" : "search",
"change #facetSorting": "sorts"
},
render: function(data) {
$(this.el).html(this.template);
return this;
},
renderList : function(facets){
$("#facetList").html("");
facets.each(function(facet){
var view2 = new facetsSearch.view.FacetsItem({
model: facet,
collection: this.collection
});
$("#facetList").append(view2.render().el);
});
return this;
},
initialize : function(){
this.template = _.template($("#list2_container_tpl").html());
this.collection.bind("reset", this.render, this);
},
search: function(e){
var letters = $("#searchFacet").val();
this.renderList(this.collection.search(letters));
},
sorts: function(e){
/*var status = $("#taskSorting").find("option:selected").val();
if (status == "") status = 0;
this.renderList(this.collection.currentStatus(status));*/
}
});
facetsSearch.view.FacetsItem = Backbone.View.extend({
events: {},
render: function(data) {
$(this.el).html(this.template(this.model.toJSON()));
console.log(this.model.toJSON(), "became", this.template(this.model.toJSON()));
return this;
},
initialize : function(){
this.template = _.template($("#facet_item_tpl").html());
}
});
</script>
<script>
Backbone.history.start();
</script>
</body>
The problem
To display Tasks above Your facets. I created two bunches of codes to render Tasks and Facets but modified the variable names respectively. Unfortunately, the former cannot be displayed.
As Emile mentioned in his detailed answer, your problem is that you're initializing multiple routers with the same route.
Since you seem to be beginning with Backbone, I'll give you a simpler answer than creating a complicated Layout (parent) view:
Just have a single handler for the specific route, and initialize both your views inside it.
It'll look something like:
myapp.router = Backbone.Router.extend({
routes: {
"": "list",
},
list: function() {
this.listContainerView = new myapp.view.TasksContainer({
collection: myapp.collection.tasks
});
$("#contentContainer").append(this.listContainerView.render().el);
this.listContainerView.sorts(); //this can be done inside the view
this.mylistContainerView = new facetsSearch.view.FacetsContainer({
collection: facetsSearch.collection.facets
});
$("#contentContainer2").append(this.mylistContainerView.render().el);
this.mylistContainerView.sorts(); //this can be done inside the view
}
});
You simply initialize 2 views in the same route.
You made 2 routers, both with an empty route. Each route is registered in Backbone.history, so when the facets router is initialized, its route overrides the tasks router route.
How to have multiple routers?
For the scope of your application, you should just start by making a single router, and handling the page with 2 lists within a parent view. Make a sort of Layout view for that page, which will handle the 2 lists:
var Layout = Backbone.View.extend({
template: _.template($('#layout-template').html()),
// keep the selector strings in a simple object
selectors: {
tasks: '.task-container',
facets: '.facet-container',
},
initialize: function() {
this.view = {
tasks: new TaskList(),
facets: new FacetList()
};
},
render: function() {
this.$el.html(this.template());
var views = this.views,
selectors = this.selectors;
this.$(selectors.tasks).append(views.tasks.render().el);
this.$(selectors.facets).append(views.facets.render().el);
return this;
}
});
Then, only one router:
var Router = Backbone.Router.extend({
routes: {
"": "list",
},
list: function() {
this.listContainerView = new Layout();
$("body").html(this.listContainerView.render().el);
}
});
This won't work with your code as-is, you'll have to incorporate the concepts yourself into your app.
Otherwise, if you really want multiple routers, you must understand that they can't share a route and that at any moment, only one route can be triggered.
When you have multiple routers, each manages the routes of a single module.
var TaskRouter = Backbone.Router.extend({
routes: {
'tasks': 'taskList',
'tasks/:id': 'taskDetails'
}
// ...snip...
});
var FacetsRouter = Backbone.Router.extend({
routes: {
'facets': 'facetList',
'facets/:id': 'facetDetails'
}
// ...snip...
});
Other improvements
Compile the template once
It's more efficient to compile the template once, when the view is being extended, than each time a new view is initialized.
myapp.view.TasksContainer = Backbone.View.extend({
// gets compiled once
template: _.template($("#list_container_tpl").html()),
initialize: function() {
// not here, as it gets compiled for each view
// this.template = _.template($("#list_container_tpl").html())
},
});
Avoid the global jQuery function
Avoid $(this.el) in favor of this.$el.
Avoid $('#divInTemplate') in favor of this.$('.divInTemplate'). It's a shortcut to this.$el.find.
See What is the difference between $el and el for additional informations.
Cache the jQuery objects
Whenever you want to select a child of the view's element, do it once and put the result in a variable.
render: function(data) {
this.$el.html(this.template);
// I like to namespace them inside an object.
this.elements = {
$list: this.$('.task-list'),
$search: this.$('.task-sorting')
};
// then werever you want to use them
this.elements.$list.toggleClass('active');
return this;
},
Use listenTo
Avoid bind/unbind and on/off/once (aliases) in favor of listenTo/stopListening/listenToOnce.
listenTo is an improved version of bind which solves problem with memory leaks.
this.collection.bind("reset", this.render, this);
// becomes
this.listenTo(this.collection, "reset", this.render);
Pass an array of objects to collection
myapp.collection.Tasks = Backbone.Collection.extend({
model: myapp.model.Tasks
// ...snip...
});
myapp.collection.tasks = new myapp.collection.Tasks([{
completed: 0,
name: "Clear dishes"
}, {
completed: 1,
name: "Get out the trash"
}, {
completed: 0,
name: "Do the laundry"
}, {
completed: 1,
name: "Vacuuming the carpet"
}]);
This would be enough, Backbone collection takes care of the rest.
I have the following a very simple ToDo List app using Backbone framework.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>To do List</title>
<style>
.completed{
text-decoration: line-through;
color: #666;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/underscore.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>
</head>
<body>
<h1>My Todos</h1>
<div id="tasks">
<button class="add">Add Task</button>
<button class="clear hide">Clear All</button>
<ul></ul>
</div>
<script id="taskTemplate" type="text/template">
<span class="<%= completed ? 'completed' : 'incomplete' %>"><%= text %></span>
<button class="complete"></button>
<button class="delete"></button>
</script>
<script type="text/javascript">
var Task = Backbone.Model.extend({
defaults: {text: 'New task', completed: false}
});
var Tasks = Backbone.Collection.extend({
model: Task,
el: '#tasks',
initialize: function(){
this.collection = new Tasks;
this.collection.on('add', this.appendNewTask, this);
this.items = this.$el.children('ul');
},
add: function(){
var text = prompt('What do you need to do?');
var task = new Task({text: text});
this.collection.add(task);
},
appendNewTask: function(task){
var TasksView = new TasksView({model:task});
this.items.append(TasksView.el);
},
completed: function(){
return _.filter(this.models, function(model){
return model.get('completed');
});
}
});
var TasksView = Backbone.View.extend({
tagName: 'li',
el: '#tasks',
template: _.template($('#taskTemplate').html()),
initialize: function(){
this.model.on('change', this.render, this);
this.model.on('remove', this.unrender, this);
this.render();
},
render: function(){
var markup = this.template(this.model.toJSON());
this.$el.html(markup);
},
unrender: function(){
this.$el.remove();
},
events: {
'click .add': 'add',
'click .clear': 'clearCompleted',
'click .delete': 'delete',
'click .complete': 'updateStatus',
'dblclick span': 'edit'
},
add: function(){
var text = prompt('What do you need to do?');
var task = new Task({text: text});
},
delete: function(){
this.model.destroy();
this.$el.remove();
},
updateStatus: function(){
this.model.set('completed', !this.model.get('completed'));
},
edit: function(){
var text = prompt('What should we change your task to?', this.model.get('text'))
this.model.set('text',text);
},
clearCompleted: function(){
var completedTasks = this.collection.completed();
this.collection.remove(completedTasks);
}
});
new TasksView;
</script>
<!-- Template JS -->
</body>
</html>
When I visit and load the page, and I could see an uncaught javascript error in the console log.
Uncaught TypeError: Cannot read property 'on' of undefined on line 78.
Looking through the code at the indictaed line number, it pointed to this
var TasksView = Backbone.View.extend({
//.....
initialize: function(){
this.model.on('change', this.render, this); // this is the line the console is complaining
this.model.on('remove', this.unrender, this);
this.render();
},
//.....
});
After staring this for the next couple of hours and analysed the code, I couldn't figure out why this model needs to be instantiated when no tasks have been added to the TaskView Objects yet. It should be initialized as soon as I add or remove a new Task item into the model. I don't quite understand how this would throw an exception.
BTW, I'm a very new to Backbone.js and Underscore.js. I'm just following an online tutorial to figure out how these frameworks work...
Thanks.
You are not binding any model to your view. You can pass a model and/or collection when instantiating your new view. These properties will automatically be bound to this.model / this.collection of your view.
You are not passing a model so this.model is undefined in your view. You should pass the empty taskslist so that when it's populated later, the onchange will be triggered and your view will rerender.
new TasksView({model: new Tasks()});
Having a simple template with backbone.js -
jsTemplateBackbone.html
<html>
<head>
<script src="jquery-2.1.0.min.js"></script>
<script src="json2.min.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<!--Order is important !!!-->
</head>
<body>
<script type="text/template" id="item-container">
<li><%= value %></li>
</script>
<script src="jsBackboneHomeView.js"></script>
</body>
</html>
jsBackboneHomeView.js
//Model
Wine = Backbone.Model.extend();
// Collection
Wines = Backbone.Collection.extend({
Model: Wine,
url: "#"
});
// Collection object
wines = new Wines([
{ name: "Robert Mondovi" },
{ name: "CakeBread" }
]);
// List
ListView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
// grabing the html template
this.template = _.template($('#item-container').html());
},
render: function () {
var el = this.$el, template = this.template;
el.empty();
wines.each(function (wine) {
el.append(template(wine.toJSON()));
});
return this;
}
});
// View
HomeView = Backbone.View.extend({
el: 'body',
initialize: function () {
this.render();
},
render: function () {
this.$el.empty();
this.$el.append("<h1>My App</h1>");
listView = new ListView();
// append two <li> on <ul> and return it
this.$el.append(this.listView.render().el);
return this;
}
});
// View instance
wineApp = new HomeView();
when I execute it , it gives an error -
Uncaught TypeError: Cannot call method 'replace' of undefined - underscore.js:1236
line 1236 - text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
What is wrong here ?
(The code taken from this tutorial . )
The property in your model is called name while it is value in your template, and thus it can't be replaced. Try :
<li><%= name %></li>
in your template.
in your ListView render function, instead of returning this, return the values you want to be available as an object,
e.g.
return({
el: el
});
I'm working on ember.js tutorial now. I got a problem on "adding child routes" chapter. My todos list is not displayed. The "todos" template outputing just fine but "todos/index" template doesn't work at all. The console does not show any errors. I guess that this is some local problem or some bug. Maybe someone has already met with a similar problem. What could be the reason of this issue? How can i solve it?
Thanks.
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Ember.js • TodoMVC</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/x-handlebars" data-template-name="todos/index">
<ul id="todo-list">
{{#each itemController="todo"}}
<li {{bind-attr class="isCompleted:completed isEditing:editing"}}>
{{#if isEditing}}
{{edit-todo class="edit" value=title focus-out="acceptChanges" insert-newline="acceptChanges"}}
{{else}}
{{input type="checkbox" checked=isCompleted class="toggle"}}
<label {{action "editTodo" on="doubleClick"}}>{{title}}</label><button {{action "removeTodo"}} class="destroy"></button>
{{/if}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="todos">
<section id="todoapp">
<header id="header">
<h1>todos</h1>
{{input type="text" id="new-todo" placeholder="What needs to be done?"
value=newTitle action="createTodo"}}
</header>
<section id="main">
{{outlet}}
<input type="checkbox" id="toggle-all">
</section>
<footer id="footer">
<span id="todo-count">
<strong>{{remaining}}</strong> {{inflection}} left</span>
<ul id="filters">
<li>
All
</li>
<li>
Active
</li>
<li>
Completed
</li>
</ul>
<button id="clear-completed">
Clear completed (1)
</button>
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
</footer>
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.2.0.js"></script>
<script src="js/libs/ember-data.js"></script>
<script src="js/app.js"></script>
<script src="js/route.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/controllers/todo_controller.js"></script>
<script src="js/controllers/todos_controller.js"></script>
<script src="js/views/edit_todo_view.js"></script>
</body>
</html>
JS:
window.Todos = Ember.Application.create();
Todos.ApplicationAdapter = DS.FixtureAdapter.extend();
Todos.Router.reopen({
rootURL: '/one/'
});
Todos.Router.map(function () {
this.resource('todos', { path: '/' });
});
Todos.TodosRoute = Ember.Route.extend({
model: function () {
return this.store.find('todo');
}
});
Todos.TodosIndexRoute = Ember.Route.extend({
model: function () {
return this.modelFor('todos');
}
});
Todos.Todo = DS.Model.extend({
title:DS.attr('string'),
isCompleted:DS.attr('boolean')
});
Todos.Todo.FIXTURES = [
{
id: 1,
title: 'Learn Ember.js',
isCompleted: true
},
{
id: 2,
title: '...',
isCompleted: false
},
{
id: 3,
title: 'Profit!',
isCompleted: false
}
];
Todos.TodosController = Ember.ArrayController.extend({
actions: {
createTodo: function () {
// Get the todo title set by the "New Todo" text field
var title = this.get('newTitle');
if (!title.trim()) { return; }
// Create the new Todo model
var todo = this.store.createRecord('todo', {
title: title,
isCompleted: false
});
// Clear the "New Todo" text field
this.set('newTitle', '');
// Save the new model
todo.save();
}
},
remaining: function () {
return this.filterBy('isCompleted', false).get('length');
}.property('#each.isCompleted'),
inflection: function () {
var remaining = this.get('remaining');
return remaining === 1 ? 'item' : 'items';
}.property('remaining'),
});
Todos.TodoController = Ember.ObjectController.extend({
actions:{
editTodo: function () {
this.set('isEditing', true);
},
acceptChanges: function () {
this.set('isEditing', false);
if (Ember.isEmpty(this.get('model.title'))) {
this.send('removeTodo');
} else {
this.get('model').save();
}
},
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
},
},
isEditing: false,
isCompleted: function(key, value){
var model = this.get('model');
if (value === undefined) {
// property being used as a getter
return model.get('isCompleted');
} else {
// property being used as a setter
model.set('isCompleted', value);
model.save();
return value;
}
}.property('model.isCompleted')
});
Technically this isn't a bug, the team figured there is no point in having an index route if you can't go any deeper in the router (this is due to the fact that the todos route and template will render, so there is no real need for the index route. That being said, if you really want it, add an anonymous function and you'll get it.
Todos.Router.map(function () {
this.resource('todos', { path: '/' },function () {});
});
https://github.com/emberjs/ember.js/issues/3995
I had this problem too. After much perplexity, the solution was to use a version of index.html that actually had the <script> wrapped <ul>, instead of the one where I was moving that block around to see if it made a difference and ended up having it nowhere.
I'm trying understand how to work with Backbone collections and to pull them inside the relative template engine created by a sub view.
This is the logic i tried in my app:
My ajax request returns me this object:
{
"products":[
{
"id":"43",
"text":"Sunset Chips",
"image":"43.png"
},{
"id":"107",
"text":"Pringles Hot & Spicy",
"image":"107.png"
}
],
"brands":[
{
"id":"132",
"text":"P&G",
"image":"132.png"
},{
"id":"27",
"text":"Kinder",
"image":"27.png"
}
]
}
I grab it with jQuery's $.ajax method and manage it for my Backbone app here in my view:
<script type="text/javascript">
var search = {};
search.app = {};
search.app.id = "#search-results";
search.product = {};
search.product.defaults = {
id:0,
text:"<?php echo __('No results here');?>",
image:"<?php echo $this->webroot;?>files/product/default.png",
};
$(function(){
var SearchApp = new Search.Views.App({
id:"#search-results"
});
var ProductList = new Search.Collections.Products();
var subView;
function parseResults (response, search) {
for (var i = response.products.length - 1; i >= 0; i--) {
ProductList.add([new Search.Models.Product(response.products[i])]);
};
subView = new Search.Views.Product ({
collection:ProductList,
id:"#product-results",
template:"#results-product-template" // solo in this.options.template
});
updateResults();
}
function updateResults () {
console.log('updateResults: Ritorno il risultato quando hunter riceve una risposta dal server');
if ($('#search-results').length == 0) {
$('div.main > section:first-child').before('<section id="search-results"></section>');
}
SearchApp.renderProductCollection(subView);
}
$('#search-results .close').on('click', function () {
$('#search-results').animate({height:0}, 500, function () {
$(this).remove();
})
});
var callbacks = {
on_response:parseResults // function presente in backbone.search.js
};
$('#hunter').hunter({url:'<?php echo $this->request->base; ?>/searches/default_search', callback:callbacks, ajax_params:{limit:10, term:'%%'}});
});
</script>
This is my Backbone application:
var Search = {
Models: {},
Collections: {},
Views: {},
Templates:{}
}
Search.Models.Product = Backbone.Model.extend({
defaults: search.product.defaults || {},
initialize:function () {
console.log("initialize Search.Models.Product");
this.on("change", function (){
console.log("chiamato evento change del Model Search.Models.Product");
});
this.on("change:text", function () {
console.log("chiamato evento change:text del Model Search.Models.Product");
});
}
});
Search.Collections.Products = Backbone.Collection.extend({
model: Search.Models.Product,
initialize:function () {
console.log("initialize Search.Collections.Products");
console.log(this);
console.log(this.length);
console.log(this.models);
}
});
Search.Views.App = Backbone.View.extend({
initialize:function () {
console.log("initialize Search.Views.App");
this.$prd = this.$('#product-results');
},
render:function () {
console.log("render Search.Views.App");
},
renderProductCollection:function (subView) {
console.log("Search.Views.App > renderProductCollection");
console.log('subView.getTemplate() => ' + subView.getTemplate());
$(this.id).html(subView.getTemplate());
}
});
Search.Views.Product = Backbone.View.extend({
initialize:function () {
console.log("initialize Search.Views.Product");
},
getTemplate:function (data) {
if (data == null || data == undefined) {
data = this.collection.toJSON() || this.model.toJSON();
}
var template = Handlebars.compile($(this.options.template).html());
console.log(data);
return '<ul id="product-results" class="w-1-4">' + template(data) + '</ul>';
},
render:function () {
console.log("render Search.Views.Product");
return this;
}
});
The Handlesbar template is simply this:
<ul class="w-1-4">
<li>
<b>Products</b>
</li>
{{#each products}}
<li>
<a href="{{url}}">
<div class="origin {{type}}" title="{{name}}"><img src="'.$this->webroot.'img/icons/16/origin/{{icon}}"></div>
</a>
<div>
{{name}}
{{#support}}{{support.name}}{{/support}}
</div>
</li>
{{/each}}
</ul>
My problem is when I try to parse the data inside the Handlesbar template, since I've parsed my data inside the sub view collection, I have an Array structured like this:
[
{
"id":"43",
"text":"Sunset Chips",
"image":"43.png"
},{
"id":"107",
"text":"Pringles Hot & Spicy",
"image":"107.png"
}
]
With this data I don't have the products object anymore due to the parseResults in the view, where I put the ajax inside the collection.
How can I parse the products array without products prop name, or how I can keep the data in the right way?
I know in my app I can do something like this to solve the problem:
var container = new array();
container['products'] = this.collection.toJSON();
data = container;
var template = Handlebars.compile($(this.options.template).html());
return '<ul id="product-results" class="w-1-4">' + template(data) + '</ul>';
But is this the right way or I'm missing something?
You do not need to use $.ajax if you are working with Backbone.
Use collection.fetch
http://backbonejs.org/#Collection-fetch
Also looks like the server is not giving you the answer as you need, so Backbone has its own parse:
http://backbonejs.org/#Collection-parse
Also I'm a fan of logic less template. So the iteration through the collection must be in the view and not in the template. Also please check this(specially point two):
http://ozkatz.github.io/avoiding-common-backbonejs-pitfalls.html
Use a collection in the right way, then to render it, in the view you could listen to the add or reset event and populate the collection in that way.
this.collection.on('add', this.render); //get model by model
this.collection.on('reset', this.render); //get all models (you need to specify in the fetch call a parameter {reset : true}