I am creating a simple application using Backbone and Laravel to manage bookings, and I'm working on a simple form to update user data for the currently signed in user.
I was wondering, is there a better, more efficient way than the way I have done, to update your model with the input data from the form?
I have created a method called update in the model, which is passed a DOM object of the form. I assume this isn't the best way to go about it.
Any help would be very much appreciated!
var Account = Backbone.Model.extend({
url: "/settings/account",
initialize: function()
{
},
update: function(form)
{
this.set({
first_name : form.find('#first-name').val(),
last_name : form.find('#last-name').val(),
email : form.find('#email').val(),
landline: form.find('#landline').val(),
mobile: form.find('#mobile').val()
});
return this.save();
}
});
var user = new Account;
var AccountView = Backbone.View.extend({
el: $("div.section"),
template: _.template($("#account-template").html()),
events: {
"submit #account": "update"
},
initialize: function()
{
_.bindAll(this, 'render', 'update');
this.render();
},
render: function()
{
$(this.el).html(this.template(this.model.toJSON()));
},
update: function()
{
var form = $(this.el).find('form#account');
user.update(form);
$(this.el).find('.alert-success').show();
return false;
}
});
var Router = Backbone.Router.extend({
routes: {
"account": "account"
},
account: function()
{
user.fetch({
success: function()
{
return new AccountView({model:user});
}
});
}
});
It is considered bad design when the model is aware of its view. I would make the update of the model orchestrated by the view.
I think the easiest way would be to do this in the view:
update: function()
{
var form = $(this.el).find('form#account');
user.set({
first_name : form.find('#first-name').val(),
last_name : form.find('#last-name').val(),
email : form.find('#email').val(),
landline: form.find('#landline').val(),
mobile: form.find('#mobile').val()
});
user.save();
$(this.el).find('.alert-success').show();
return false;
}
Otherwise the model would have to know where to retrieve the values. Also, when you someday use a different view you would also have to change the model class.
Related
I've created a search bar, but when the data is gathered from the user, it displays the default data over again rather then the users new search criteria.
I'm resetting the collection and giving it a new URL when the user searches, but it doesn't seem to update correctly, and I'm having trouble figuring out where my problem(s) are.
(function(){
'use strict';
var red = red || {};
//model////////////////////////////////////////////////
red.RedditModel = Backbone.Model.extend({
defaults: {
urlTarget: $('#textBox').val(),
urlStart: 'https://www.reddit.com/r/',
urlEnd: '.json'
},
initialize: function() {
this.on('change:urlTarget', function() {
console.log('The Url Target has changed to ' + this.get("urlTarget"));
});
this.on('change:concatURL', function() {
console.log('The model Url has changed to ' + this.get("concatURL"));
});
this.on('change:url', function() {
console.log('The collection url has changed to: ' + this.get('url'));
});
}
});
var redditModel = new red.RedditModel();
var fullURL = new red.RedditModel({
concatURL: redditModel.attributes.urlStart + redditModel.attributes.urlTarget + redditModel.attributes.urlEnd
});
var listElmement,
$list = $('.list');
//collections//////////////////////////////////////////
red.redditCollection = Backbone.Collection.extend({
model: red.RedditModel,
url: fullURL.attributes.concatURL,
parse: function(response) {
var redditData = response.data.children;
return redditData;
}
});
//view////////////////////////////////////
red.RedditView = Backbone.View.extend({
model: fullURL,
collection: redditCollection,
el: '.searchBar',
events: {
'click .searchButton': function(e) {
this.updateModel(e);
this.updateCollection(e);
},
'change #textBox': 'initialize'
},
updateModel: function() {
this.$urlTarget = $('#textBox').val()
this.model.set('urlTarget', this.$urlTarget);
this.model.set('concatURL', redditModel.attributes.urlStart + this.$urlTarget + redditModel.attributes.urlEnd);
},
updateCollection: function() {
this.collection.reset();
this.$urlTarget = $('#textBox').val();
var newUrl = redditModel.attributes.urlStart + this.$urlTarget + redditModel.attributes.urlEnd;
this.collection.add({ urlTarget: this.$urlTarget });
this.collection.add({ url: newUrl });
console.log(newUrl);
},
tagName: 'li',
className: 'listItems',
initialize: function() {
$list.html('');
this.collection.fetch({
success: function(redditData) {
redditData.each(function(redditData) {
redditData = redditData.attributes.data.title
listElmement = $('<li></li>').text(redditData);
$list.append(listElmement);
})
}
});
},
render: function() {
}
});
var redditCollection = new red.redditCollection({
redditModel,
fullURL
});
var myRedditView = new red.RedditView({
model: redditModel,
collection: redditCollection
});
$('.page').html(myRedditView.render());;
})();
Parse within the model, and use it for its intended purpose. No need to store the reddit url and other search related info in a model.
red.RedditModel = Backbone.Model.extend({
parse: function(data) {
return data.data;
},
})
Since you already take care of the reddit url here. Don't be afraid to make yourself some utility functions and getters/setters in your Backbone extended objects (views, model, collection, etc).
red.RedditCollection = Backbone.Collection.extend({
url: function() {
return 'https://www.reddit.com/r/' + this.target + this.extension;
},
initialize: function(models, options) {
this.extension = '.json'; // default extension
},
setExtension: function(ext) {
this.extension = ext;
},
setTarget: function(target) {
this.target = target;
},
parse: function(response) {
return response.data.children;
}
});
Don't be afraid to have a lot of views, Backbone views should be used to wrap small component logic.
So here's the item:
red.RedditItem = Backbone.View.extend({
tagName: 'li',
className: 'listItems',
render: function() {
this.$el.text(this.model.get('title'));
return this;
}
});
Which is used by the list:
red.RedditList = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
},
render: function() {
this.$el.empty();
this.collection.each(this.renderItem, this);
return this;
},
renderItem: function(model) {
var view = new red.RedditItem({ model: model });
this.$el.append(view.render().el);
}
});
And the list is just a sub-component (sub-view) of our root view.
red.RedditView = Backbone.View.extend({
el: '.searchBar',
events: {
'click .searchButton': 'onSearchClick',
},
initialize: function() {
// cache the jQuery element for the textbox
this.$target = $('#textBox');
this.collection = new red.RedditCollection();
this.list = new red.RedditList({
collection: this.collection,
// assuming '.list' is within '.searchBar', and it should
el: this.$('.list'),
});
},
render: function() {
this.list.render();
return this;
},
onSearchClick: function(e) {
this.collection.setTarget(this.$target.val());
console.log(this.collection.url());
this.collection.fetch({ reset: true });
},
});
Then, you only need the following to use it:
var myRedditView = new red.RedditView();
myRedditView.render();
Notice the almost non-existent use of the global jQuery selector. If you're using Backbone and everywhere you're using $('#my-element'), you're defeating the purpose of Backbone which is, in part, to apply MVC concepts on top of jQuery.
Some notes on the code posted
Take time to understand what's going on. There are several lines of code in your question that doesn't do anything, or just don't work at all.
Though it's been removed in your answer, the following doesn't make sense because the collection constructor is Backbone.Collection([models], [options]) and what you have here translates to passing an options object (using ES6 shorthand property names { a, b, c}) to the models parameter.
var redditCollection = new red.redditCollection({
redditModel,
fullURL
});
This line does nothing, because .render() doesn't do anything and doesn't return anything.
$('.page').html(myRedditView.render());
Here, you're creating a new element manually using jQuery while you have Backbone which does this for you.
$('<li></li>').text(redditData);
Don't use the attributes directly, always use .get('attributeKey') unless you have a good reason not to.
redditModel.attributes.urlStart
Favor local variables whenever you can. The listElement var here is defined at the "app" level without a need for it.
listElmement = $('<li></li>').text(redditData);
$list.append(listElmement);
A Backbone collection is automatically filled with the new instances of models on success. You do not need to re-parse that in the success callback (in addition to the ambiguity with redditData).
this.collection.fetch({
success: function(redditData) {
redditData.each(function(redditData) {
redditData = redditData.attributes.data.title;
I don't mean to be rude and I took the time to write that long answer to try to help, you, and any future reader that comes by.
I am creating a crud web app with backbone. I am writing the functionality to update a resource (PUT). I am trying to achieve this by fetching a models properties from the server (see the SubscriberView) and on successfully fetching the resource to instantiate a SubscriberEditView whereby the newly fetched model is passed.
So far this works as expected; SubscriberEditView renders an html form which is populated with the model instance properties.
When I enter a new login value into the form I can trigger the update function which successfully makes a PUT request to the server resource and updates the model instance as expected.
However, the problem is that when I then repeat this process with another model instance the PUT request is made against the curent model AND the previously instantiated model.
Is the reason for this because I now have two instances of SubscriberEditView? Or is it something else that I have missed/misunderstood.
Please see below the described code.
// The view for a single subscriber
var SubscriberView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#subscribers-tmpl').html()),
initialize: function() {
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
var html = this.template(this.model.toJSON());
this.$el.html(html);
return this;
},
events: {
'click .remove': 'onRemove',
'click .edit-subscriber': 'editSubscriber',
},
editSubscriber: function() {
var getSubscriberModel = this.model.set('id', this.model.attributes.id, {silent:true})
getSubscriberModel.fetch({
success: function (model, response) {
$('#addSubscriber').fadeOut();
new SubscriberEditView({model:model});
},
error: function (response) {
console.log('There was an error');
}
});
},
onRemove: function() {
this.model.destroy();
}
});
// The edit view
var SubscriberEditView = Backbone.View.extend({
tagName: 'div',
el: '#updateSubscriber',
template: _.template($('#subscriberEdit-tmpl').html()),
initialize: function() {
this.model.on('sync', this.render, this);
},
events: {
'click #close': 'cancel',
'click .save-subscriber': 'update'
},
update: function() {
var $login = this.$('#login');
this.model.save({
login: $login.val(),
},
{
dataType: 'text',
success: function (model, response, options) {
console.log('success');
},
error: function (model, response, options) {
console.log('error');
}
});
},
cancel: function() {
$('#addSubscriber').fadeIn();
$('#editInner').fadeOut();
},
render: function() {
var html = this.template(this.model.toJSON());
this.$el.html(html);
},
});
If anyone could help then that would be greatly appreciated.
Cheers
The issue is el: '#updateSubscriber',. All your view instances are pointing to same element to which events are delegated. So clicking on any of the .save-subscriber will trigger update for all the view instances. You should not specify el for a view that is going to have more than one instance.
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
I've been working through Code School's Anatomy of Backbone.js course, but am confused when trying to save model changes back to the server. Perhaps you can help.
This is what I understand needs to happen:
Populate collection from a JSON data source using fetch();
Append the collection to the DOM
Edit a model (uncheck checkbox, which sets 'favourite' to false)
Save the model.
My assumption is that if I were to unselect a record as a 'favourite' then hit refresh, the change would be persistant and also evident in the JSON file. However, this isn't the case and the original collection is loaded and JSON is unchanged.
I think my confusion is in using the fetch method and declaring the URL within the model and collection.
How can I get this model change to be persistant?
Model:
var Contact = Backbone.Model.extend({
url: '/contacts',
defaults:{
favourite: false
},
toggleFavourite: function(){
if(this.get('favourite') === false)
{
this.set({ 'favourite': true });
} else {
this.set({ 'favourite': false })
}
this.save();
}
});
Collection
var Contacts = Backbone.Collection.extend({
model: Contact,
url: '/contacts'
});
Views
var ContactView = Backbone.View.extend({
className: 'record',
template: _.template('<span><%= name %></span>' +
'<span class="phone-number"><%= phone %></span>' +
'<input type="checkbox" <% if(favourite === true) print("checked") %>/>'),
events: {
'change input': 'toggleFavourite',
'click .phone-number': 'dial'
},
initialize: function(){
this.model.on('change', this.render, this);
},
toggleFavourite: function(e){
this.model.toggleFavourite();
},
dial: function(e){
alert('Dialing now...');
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var ContactsView = Backbone.View.extend({
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(contact){
var contactView = new ContactView({ model: contact });
this.$el.append(contactView.render().el);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
render: function(){
this.addAll();
}
});
App.js
var contacts = new Contacts(); //creates list
contactsView = new ContactsView({ collection: contacts}); //creates list view
contacts.fetch({url: 'contacts/data.json'}); //populates list
$('#mainPanel').append(contactsView.el); //appends list to DOM
Backbone works on client, and can't change file on server itself.
You need to store dynamic data somewhere on server (maybe mongodb if you use json it will be easier).
contacts/data.json named static file. because it is not changing while you did't owerwrite it on the server.
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
});