I am probably missing something easy or doing something wrong, but I am trying this and can't get it to fire the function...
var Home = Backbone.View.extend({
indexAction: function() {
console.log('index');
},
render: function() {
console.log('render');
}
});
Home.indexAction();
All I get is this error:
Uncaught TypeError: Object function (){return i.apply(this,arguments)}
has no method 'indexAction'
You created the view type but did not create an instance.
You need to instantiate a view of type Home now:
var h = new Home();
h.indexAction();
Also, it might be better to rename Home as HomeView, so you know it's a view which can be instantiated.
var HomeView = Backbone.View.extend({
indexAction: function() {
console.log('index');
},
render: function() {
console.log('render');
}
});
var home = new HomeView();
example on backbone docs
Related
I have several Backbone Models rendered in a Collection View, and also I have a route that should render a view of that model. So, here come the views
resume.js
// this renders a single model for a collection view
var ResumeView = Backbone.View.extend({
model: new Resume(),
initialize: function () {
this.template = _.template($('#resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON));
return this;
}
});
#resume template
<section id="resume">
<h1><%= profession %></h1>
<!-- !!!!! The link for a router which should navigate to ShowResume view -->
View Details
</section>
Collection view:
var ResumeList = Backbone.View.extend({
initialize: function (options) {
this.collection = options.collection;
this.collection.on('add', this.render, this);
// Getting the data from JSON-server
this.collection.fetch({
success: function (res) {
_.each(res.toJSON(), function (item) {
console.log("GET a model with " + item.id);
});
},
error: function () {
console.log("Failed to GET");
}
});
},
render: function () {
var self = this;
this.$el.html('');
_.each(this.collection.toArray(), function (cv) {
self.$el.append((new ResumeView({model: cv})).render().$el);
});
return this;
}
});
The code above works perfectly and does exactly what I need -- an array of models is fetched from my local JSON-server and each model is displayed within a collection view. However, the trouble starts when I try to navigate through my link in the template above. Here comes the router:
var AppRouter = Backbone.Router.extend({
routes: {
'': home,
'resumes/:id': 'showResume'
},
initialize: function (options) {
// layout is set in main.js
this.layout = options.layout
},
home: function () {
this.layout.render(new ResumeList({collection: resumes}));
},
showResume: function (cv) {
this.layout.render(new ShowResume({model: cv}));
}
});
and finally the ShowResume view:
var ShowResume = Backbone.View.extend({
initialize: function (options) {
this.model = options.model;
this.template = _.template($('#full-resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
}
});
I didn't provide the template for this view because it is quite large, but the error is following: whenever I try to navigate to a link, a view tries to render, but returns me the following error: Uncaught TypeError: this.model.toJSON is not a function. I suspect that my showResume method in router is invalid, but I can't actually get how to make it work in right way.
You are passing the string id of the url 'resumes/:id' as the model of the view.
This should solve it.
showResume: function (id) {
this.layout.render(new ShowResume({
model: new Backbone.Model({
id: id,
profession: "teacher" // you can pass data like this
})
}));
}
But you should fetch the data in the controller and react accordingly in the view.
var AppRouter = Backbone.Router.extend({
routes: {
'*otherwise': 'home', // notice the catch all
'resumes/:id': 'showResume'
},
initialize: function(options) {
// layout is set in main.js
this.layout = options.layout
},
home: function() {
this.layout.render(new ResumeList({ collection: resumes }));
},
showResume: function(id) {
// lazily create the view and keep it
if (!this.showResume) {
this.showResume = new ShowResume({ model: new Backbone.Model() });
}
// use the view's model and fetch
this.showResume.model.set('id', id).fetch({
context: this,
success: function(){
this.layout.render(this.showResume);
}
})
}
});
Also, this.model = options.model; is unnecessary as Backbone automatically picks up model, collection, el, id, className, tagName, attributes and events, extending the view with them.
I am trying to write a simple example using Backbone.js for study. Some how nothing gets printed in the browser. Need a little help here. The code is given below.
Html:
<div id="container">
<ul id="person-list">
</ul>
</div>
Models
var Person = Backbone.Model.extend({
defaults: {
id: 0,
name: ''
}
});
var PersonStore = Backbone.Collection.extend({
model: Person,
url: 'api/person', //currently not using
initialize: function () {
console.log("Store initialize");
}
});
Views
var PersonView = Backbone.View.extend({
tagName: 'li',
initialize: function () {
_.bindAll(this, "render");
},
render: function () {
$(this.el).append(this.model.name) //model.name shows undefined here
return this;
}
});
var PersonListView = Backbone.View.extend({
el: $('#person-list'),
tagName:'ul',
initialize: function () {
_.bindAll(this, "render");
this.render();
},
render: function () {
self = this;
this.collection.each(function (person) { //name property undefined here on person
var personView = new PersonView({ model: person });
$(self.el).append(personView.render().el);
});
}
});
Sample Run
var persons = new PersonStore([
new Person({id:1, name: "Person 1"}),
new Person({ id: 2, name: "Person 2" }),
]);
new PersonListView({ collection: persons });
The above setup prints nothing(blank) on screen. I have struggled now for some time and need a little help here as to why the two Person's name does not get displayed in the browser.
To make your code work you have to replace
this.$el.append(this.model.name)
with
this.$el.append(this.model.get('name'))
Always use method .get() to access model properties.
Also i highly recommend you use templates for rendering views. This approach let you write .render() implementation once and will be no need to change it if you need visual changes, you can make in template
http://jsfiddle.net/3pSg7/
I wonder if someone can help to find what's wrong in this case.
I get "Uncaught ReferenceError: text is not defined" in line 6.
Using template and local .txt files for testing until APIs are available.
Backbone.js model script:
var Letter = Backbone.Model.extend( {
urlRoot: 'data/json/news',
initialize: function() {
},
defaults: {
_type: "",
text: "",
is_read: 0
}
});
var News = Backbone.Collection.extend({
model: Letter,
url: 'data/json/list_news.txt',
initialize: function() {
},
fetchMyNews: function() {
this.fetch({async:false});
}
});
var news = new News();
View script:
var NewsView = Backbone.View.extend({
initialize: function() {
this.isShown = false;
this.render();
this.listenTo(news, "all", this.doListen);
},
doListen: function(eventName){
if(eventName == "change"){
this.render();
}
},
isShown: false,
events: {
},
render: function() {
this.$el.attr("z-index", "1000");
news.fetchMyNews();
var sHtml = JST["news/row"](news.attributes);
$("#news_tbody").html(sHtml);
}
});
a few things in your code.
you are defining a global variable 'news' for your collection. that's not recommend, you can just pass a new collection to your view when you instantiate it :
var NewsView = new NewsView({
collection: new News()
});
and change all your 'news' reference in the view to 'this.collection'
and, I usually don't like async ajax calls. try to change them to callbacks, or just listen to events in your view. oh, and also, try not to fetch data in your render(). your function should only do what they are named for. :)
so in your view:
initialize: function() {
this.isShown = false;
this.listenTo(this.collection, "all", this.doListen);
this.collection.fetch();
},
doListen: function(eventName){
if(eventName == "change" || eventName == 'reset'){
this.render();
}
}
and in your render:
var sHtml = JST["news/row"](new.attributes);
$("#news_tbody").html(sHtml);
you are calling news.attributes, news is a collection here..."attributes" doesn't give you anything. I'm not sure what your template looks like, but you may be calling '.text' in your template, which is giving your this error here since news.attributes is undefined.
For some reasons, I keep on getting this error, (See attached screenshot). I've tried adding a _.bindAll(this); and even tried upgrading my code to have the latest version of backbonejs. Still no luck.
Can someone help me on this?
var app = app || {};
(function ($) {
'use strict';
app.EmployeeView = Backbone.View.extend({
el: '#container',
model: app.Employee,
events: {
'click #save' : 'saveEntry'
},
initialize: function(){
console.log('Inside Initialization!');
this.$empName = this.$('#txtEmpName');
this.$department = this.$('#txtDepartment');
this.$designation = this.$('#txtDesignation');
this.listenTo(app.employees, 'add', this.addEmployee);
app.employees.fetch();
console.log('End of Initialization!');
//this.render();
},
render: function () {
console.log('Inside Render!!');
console.log(this.model);
this.$el.html(this.template(this.model.toJSON()));
console.log('Inside End of Render!!');
return this;
},
newAttributes: function(){
return{
empName: this.$empName.val(),
department: this.$department.val(),
designation: this.$designation.val()
};
},
saveEntry: function(){
console.log('Inside SaveEntry!');
//console.log(this.newAttributes());
console.log('this.model');
console.log(app.Employee);
//app.employees.create(this.newAttributes());
app.Employee.set(this.newAttributes());
app.employees.add(app.Employee);
console.log('After SaveEntry!');
},
addEmployee: function (todo) {
var view = new app.EmployeeItemView({ model: app.Employee });
$('#empInfo').append(view.render().el);
}
})
})(jQuery);
Code for "collections/employees.js"
var app = app || {};
(function (){
console.log('Inside collection');
var Employees = Backbone.Collection.extend({
model: app.Employee,
localStorage: new Backbone.LocalStorage('employee-db')
});
app.employees = new Employees();
})();
Code for "model/employee.js"
var app = app || {};
(function(){
'use strict';
app.Employee = Backbone.Model.extend({
defaults: {
empName: '',
department: '',
designation: ''
}
});
})();
You're saying this in your view:
model: app.Employee
app.Employee looks like a model "class" rather than a model instance. Your view wants a model instance in its model property. Normally you'd say something like this:
var employee = new app.Employee(...);
var view = new app.EmployeeView({ model: employee });
this.model.toJSON() won't work since this.model is the app.Employee constructor. Actually I don't see any meaning in your EmployeeView.render method. If it is aggregate view why you have model on it? Otherwise what is the second view class EmployeeItemView? If you're following ToDo MVC example you can see that there is no model in AppView, that is why I conclude you need not model in your EmployeeView. And render method you provided seems to belong to EmployeeItemView.
Secondly, you call app.Employee.set which is also a call on a constructor not on an object. I think you meant
saveEntry: function(){
console.log('Inside SaveEntry!');
app.employees.create(this.newAttributes());
console.log('After SaveEntry!');
},
If you want to pass a model to app.EmployeeItemView you should use callback argument.
addEmployee: function (employee) {
var view = new app.EmployeeItemView({ model: employee });
$('#empInfo').append(view.render().el);
}
I've looked everywhere for an answer but wasn't satisfied with what I've found.
The issue is, I'm doing a tutorial from Addy Osmani to make a 'Todo' app in Backbone, but when I look at the console, I get an error saying that this.model is undefined.
I even tried this SO answer Backbone model error displayed in console, but I still get the same error. Please tell me what is wrong.
By the way, what are this.model or this.collection? I've got an idea that they refer to Backbone.Model and Backbone.Collection but how do they work? I'm asking this because in another tutorial this.collection and this.model.models were also undefined, when I've clearly defined the Model and Collection.
Many Thanks
JS:
//Model
var Todo = Backbone.Model.extend({
defaults: {
title: 'Enter title here',
completed: true
},
validate: function(attrs) {
if (attrs.title === undefined) {
return 'Remember to enter a title';
}
},
initialize: function() {
console.log('This model has been initialized');
this.on('change:title', function() {
console.log('-Title values for this model have changed');
});
this.on('invalid', function(model, error) {
console.log(error);
});
}
});
//View
var TodoView = Backbone.View.extend({
el: '#todo',
tagName: 'li',
template: _.template($('#todoTemplate').html()),
events: {
'dbclick label': 'edit',
'click .edit': 'updateOnEnter',
'blur .edit': 'close'
},
initialize: function() {
_.bindAll(this, 'render');
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.input = this.$('.edit');
console.log(this.model.toJSON());
return this;
},
edit: function() {
//do something...
},
close: function() {
//do something...
},
updateOnEnter: function() {
//do something...
}
});
var todoview = new TodoView();
console.log(todoview.el);
//Collection
var TodoList = Backbone.Collection.extend({
model: Todo
});
You need to instantiate a Model or Collection and pass it to your View. Otherwise, when the render method is called on your TodoView, this.model will be null.
For example, try rearranging the last few lines of your code like this:
//Collection
var TodoList = Backbone.Collection.extend({
model: Todo
});
var todos = new TodoList();
var todoview = new TodoView({model: todos});
From that point onward, you can modify todos (which is a Collection) and your view can listen to todos' events and re-render accordingly.
The answer in the other question is the answer to your question: you're not passing the model to the view when you instantiate the view.
var model = new Todo();
var todoview = new TodoView({model: model});
When you pass an object to a view's constructor, it looks for certain keys and attaches them directly to the view.
You can see which by looking at Backbone's source and searching for viewOptions.
That's how you get the this.model and this.collection automatically attached to the view's this.
You didn't say, but I assume the error you are getting is occurring in the render() method.
Your problem is that you define a new type of model (var Todo = Backbone.Model.extend({...) however you never instantiate it, nor do you pass the model to the todoview constructor.
So at the very least you need to do:
var todomodel = new Todo();
var todoview = new TodoView({
model: todomodel
});