Getting a json from collection to view in backbone.js - javascript

I am new to backbone.js and is having some problem with my app. I have a collection which relies on a json data source. I am able to console.log the json in my parse method. Is that enough to bind the collection to my view? I don't understand the use of fetch method.
My collection looks like as follows,
(function (collections,model) {
collections.Directory = Backbone.Collection.extend({
initialize : function(){
console.log('we are here');
},
model:model.item,
url:'collections/json/data.json',
parse:function(response){
console.log(response);
return response;
}
});
})(app.collections,app.models);
And my master view looks like this,
(function(views,collections){
views.masterView = Backbone.View.extend({
el : $("#contacts"),
initialize : function(){
console.log('view initialize inside render');
this.render();
this.$el.find("#filter").append(this.createSelect());
this.on("change:filterType", this.filterByType, this);
this.collection.on("reset", this.render, this);
this.collection.on("add", this.renderContact, this);
//console.log('we are here'+app.collections.CollectionItems.fetch());
console.log('view initialize');
},
render : function(){
this.$el.find("article").remove();
_.each(this.collection.models,function(item){
this.renderContact(item);
},this);
},
renderContact: function (item) {
views.contactView = new app.views.ContactView({
model: item
});
this.$el.append(contactView.render().el);
},
getTypes : function () {
return _.uniq(this.collection.pluck("Qno"));
},
createSelect : function () {
var select = $("<select/>", {
html: "<option value='all'>All</option>"
});
_.each(this.getTypes(), function (item) {
var option = $("<option/>", {
value: item.toLowerCase(),
text: item.toLowerCase()
}).appendTo(select);
});
return select;
},
events: {
"change #filter select": "setFilter",
"click #add": "addContact",
"click #showForm": "showForm"
},
setFilter : function(e){
this.filterType = e.currentTarget.value;
this.trigger("change:filterType");
},
filterByType: function () {
if (this.filterType === "all") {
this.collection.reset(contacts);
routerURL.navigate("filter/all");
} else {
this.collection.reset(contacts, { silent: true });
var filterType = this.filterType,
filtered = _.filter(this.collection.models, function (item) {
return item.get("type").toLowerCase() === filterType;
});
this.collection.reset(filtered);
routerURL.navigate("filter/"+filterType);
}
},
addContact : function(e){
e.preventDefault();
var contModel = {};
$("#addContact").children("input").each(function(i, el){
if($(el).val() !== "")
contModel[el.id] = $(el).val();
});
contacts.push(contModel);
if (_.indexOf(this.getTypes(), contModel.type) === -1) {
this.collection.add(new Contact(contModel));
this.$el.find("#filter").find("select").remove().end().append(this.createSelect());
} else {
this.collection.add(new Contact(contModel));
}
},
showForm : function(){
this.$el.find("#addContact").slideToggle();
}
});
})(app.views,app.collections);
my model is very simple and looks like this,
(function ( models ) {
models.Item = Backbone.Model.extend({
defaults :{Qno:'1',Desc:'hello'}
});
})( app.models );
ihave one js file instantiatin viewsand collections
(function () {
window.app = {};
app.collections = {};
app.models = {};
app.views = {};
app.mixins = {};
$(function(){
app.collections.CollectionItems = new app.collections.Directory();
//app.collections.CollectionItems.fetch();
//console.log(app.collections.CollectionItems.fetch());
app.collections.CollectionItems.fetch({
success: function (collection,response) {
console.log(response);
}
});
//console.log(app.collections.CollectionItems.toJSON());
console.log('coll started');
app.views.app = new app.views.masterView({collection: app.collections.CollectionItems});
console.log('view is jus about fine!!');
//app.views.pagination = new app.views.PaginatedView({collection:app.collections.paginatedItems});
});
var ContactsRouter = Backbone.Router.extend({
routes: {
"filter/:type": "urlFilter"
},
urlFilter: function (type) {
master.filterType = type;
master.trigger("change:filterType");
}
});
var routerURL = new ContactsRouter();
Backbone.history.start();
})();
my landing page looks like this with a template in it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Backbone.js Web App</title>
<link rel="stylesheet" href="css/screen.css" />
</head>
<body>
<div id="contacts">
</div>
<script id="contactTemplate" type="text/template">
<h1><%= Qno %></h1>
</script>
<script src="js/jquery.js"></script>
<script src="js/underscore-min.js"></script>
<script src="js/backbone-min.js"></script>
<script src="app.js"></script>
<script src="collections/Directory.js"></script>
<script src="models/item.js"></script>
<script src="views/masterView.js"></script>
<script src="views/simpleView.js"></script>
<!--<script src="js/backbone.paginator.js"></script>-->
</body>
</html>
I just can't get my head around this. The view is not rendered with the collection data. Please help!

I think it's because the fetch method on your collection is executed asynchronously and has therefore not completed when you create your view (if you look at the console I would expect the log statement in the success callback to display after the log statements underneath). This means that your view render method is called before the collection is populated and the reset event (which you're binding to in your view) is never triggered.
Try updating the code which instantiates everything as follows:
$(function(){
app.collections.CollectionItems = new app.collections.Directory();
//app.collections.CollectionItems.fetch();
//console.log(app.collections.CollectionItems.fetch());
app.collections.CollectionItems.fetch({
success: function (collection,response) {
console.log(response);
app.views.app = new app.views.masterView({collection: app.collections.CollectionItems});
}
});
});

Related

id is not defined at child.eval

I'm writing my first Backbone blog app but when i try to add new post it throws an error.
Here is my app.js (all of backbone related components are in this file):
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var Post = Backbone.Model.extend({});
var Posts = Backbone.Collection.extend({
model : Post,
url : "/posts"
});
var PostListView = Backbone.View.extend({
tagName: "li",
template: _.template("<a href='/posts/{{id}}'>{{title}}</a>"),
events: {
'click a': 'handleClick'
},
handleClick: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"),
{trigger: true});
},
render: function () {
this.el.innerHTML = this.template(this.model.toJSON());
return this;
}
});
var PostsListView = Backbone.View.extend({
template: _.template("<h1>My Blog</h1><a href='/post/new' class='newPost'>New</a> <ul></ul>"),
events: {
'click .newPost': 'handleNewClick'
},
handleNewClick: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"),
{trigger: true});
},
render: function () {
this.el.innerHTML = this.template();
var ul = this.$el.find("ul");
this.collection.forEach(function (post) {
ul.append(new PostListView({
model: post
}).render().el);
});
return this;
}
});
var PostView = Backbone.View.extend({
template: _.template($("#postView").html()),
events: {
'click a': 'handleClick'
},
render: function () {
var model = this.model.toJSON();
model.pubDate = new Date(Date.parse(model.pubDate)).toDateString();
this.el.innerHTML = this.template(model);
return this;
},
handleClick: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"),
{trigger: true});
return false;
}
});
var PostFormView = Backbone.View.extend({
tagName: 'form',
template: _.template($("#postFormView").html()),
initialize: function (options) {
this.posts = options.posts;
},
events: {
'click #submitPost': 'createPost',
'click .back' : 'backButton'
},
render: function () {
this.el.innerHTML = this.template();
return this;
},
backButton: function (e) {
e.preventDefault();
postRouter.navigate($(e.currentTarget).attr("href"),
{trigger: true});
return false;
},
createPost: function (e) {
e.preventDefault();
var postAttrs = {
content: $("#postText").val(),
title: $("#postTitle").val(),
pubDate: new Date(),
};
this.posts.create(postAttrs);
postRouter.navigate("/", { trigger: true });
return false;
}
});
var PostRouter = Backbone.Router.extend({
initialize: function (options) {
this.posts = options.posts;
this.main = options.main;
},
routes: {
'': 'index',
'posts/:id': 'singlePost',
'post/new': 'newPost'
},
index: function () {
var pv = new PostsListView({ collection: this.posts });
this.main.html(pv.render().el);
},
singlePost: function (id) {
var post = this.posts.get(id);
var pv = new PostView({ model: post });
this.main.html(pv.render().el);
},
newPost: function () {
var pfv = new PostFormView({ posts: this.posts });
this.main.html(pfv.render().el);
}
});
I also have some view templates in my index file :
<!DOCTYPE html>
<html>
<head>
<title> Simple Blog </title>
</head>
<body>
<div id="main"></div>
<script src="/jquery.js"></script>
<script src="/underscore.js"></script>
<script src="/backbone.js"></script>
<script type="text/template" id="postFormView">
All Posts<br />
<input type="text" id="postTitle" placeholder="post title" />
<br />
<textarea id="postText"></textarea>
<br />
<button id="submitPost"> Post </button>
</script>
<script type="text/template" id="postView">
<a href='/'>All Posts</a>
<h1>{{title}}</h1>
<p>{{pubDate}}</p>
{{content}}
</script>
<script src="/app.js"></script>
<script>
var postRouter = new PostRouter({
posts: new Posts(<%- posts %>),
main: $("#main")
});
Backbone.history.start({pushState: true});
</script>
</body>
</html>
Viewing posts and home page works fine but when I try to create a new post I get this error from the dev tools console:
Uncaught ReferenceError: id is not defined
at child.eval (eval at _.template (http://localhost:3000/underscore.js:1:1), <anonymous>:6:8)
at child.template (http://localhost:3000/underscore.js:1214:21)
at child.render (http://localhost:3000/app.js:27:34)
at http://localhost:3000/app.js:48:16
at Array.forEach (native)
at Function._.each._.forEach (http://localhost:3000/underscore.js:79:11)
at child.Collection.(anonymous function) [as forEach] (http://localhost:3000/backbone.js:956:24)
at child.render (http://localhost:3000/app.js:45:25)
at child.index (http://localhost:3000/app.js:118:27)
at Object.callback (http://localhost:3000/backbone.js:1242:30)
The server is a simple nodejs server and output for creating a post is something like this:
{"result":{"ok":1,"n":1},"ops":[{"content":"kljhlkjh","title":"jkhjklh","pubDate":"2016-10-29T10:21:47.793Z","id":12,"_id":"5814783b732bbe153461eca4"}],"insertedCount":1,"insertedId
s":["5814783b732bbe153461eca4"]}
Where is the error?
First, you need to find what is causing the error, and where does it comes from.
The error comes from the following line inside the PostListView's render function:
this.el.innerHTML = this.template(this.model.toJSON());
And the error is thrown by underscore's template rendering. Which comes down to:
template: _.template("<a href='/posts/{{id}}'>{{title}}</a>"),
See the {{id}}? It's that one that is not defined when the error occurs.
What "{{id}} not defined" means?
You're passing this.model.toJSON() as the data for the template. So, it means that this.model's id attribute is not defined yet.
Why is my model id not defined yet?
It's because creating a new model through the collection's create function is asynchronous.
this.posts.create(postAttrs);
// the model hasn't received an id from the server yet.
postRouter.navigate("/", { trigger: true });
How to wait after a collection's create call?
Backbone offers success and error callbacks for most (if not all) its asynchronous functions.
The options hash takes success and error callbacks which will both be
passed (collection, response, options) as arguments.
So, you could change your createPost function to the following, adding a onPostCreated callback.
createPost: function(e) {
e.preventDefault();
var postAttrs = {
content: $("#postText").val(),
title: $("#postTitle").val(),
pubDate: new Date(),
};
this.posts.create(postAttrs, {
context: this,
success: this.onPostCreated
});
return false;
},
onPostCreated: function() {
// you don't need to use the router, so your views are self-contained
Backbone.history.navigate("/", { trigger: true });
},

Select2 4 custom data adapter

I am trying to create a custom data adapter according to an example here: http://select2.github.io/announcements-4.0.html#query-to-data-adapter.
How can I move the line that creates the select2 control outside the function with definition of DataAdapter (see the code below)?
<!DOCTYPE html>
<head>
<title></title>
<link href="select2.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="select2.full.js"></script>
<script type="text/javascript">
$.fn.select2.amd.require(
['select2/data/array', 'select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {results: []};
data.results.push({id: params.term, text: params.term});
data.results.push({id: 11, text: 'aa'});
data.results.push({id: 22, text: 'bb'});
callback(data);
};
// Works if uncommented, but this line needs to be elsewhere (in $(document).ready()).
//$("#my").select2({tags: true, dataAdapter: CustomData});
});
$(document).ready(function() {
// This line does not work here.
$("#my").select2({tags: true, dataAdapter: CustomData});
});
</script>
</head>
<body>
<select id="my"></select>
</body>
</html>
you define it via AMD-Pattern:
$.fn.select2.amd.define('select2/data/customAdapter',[
'select2/data/array',
'select2/utils'
],
function (ArrayAdapter, Utils) {
function CustomDataAdapter ($element, options) {
CustomDataAdapter.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomDataAdapter, ArrayAdapter);
CustomDataAdapter.prototype.current = function (callback) {
callback(...);
};
return CustomDataAdapter;
}
);
var customAdapter=$.fn.select2.amd.require('select2/data/customAdapter');
$("#my").select2({
tags: true,
dataAdapter: customAdapter
});
For anyone trying to extend select2, here is an example :
// Require the adapter you want to override
$.fn.select2.amd.require(["select2/data/select"], function (Select) {
let CustomDataAdapter = Select;
// Simple example, just override the function
CustomDataAdapter.prototype.current = function (callback) {
// Your own code
};
// Example modifying data then calling the original function (which we need to keep)
let originalSelect = CustomDataAdapter.prototype.select;
CustomDataAdapter.prototype.select = function (data) {
// Your own code
// Call the original function while keeping 'this' context
originalSelect.bind(this)(data);
};
// Finally, use the custom data adapter
$('#my-select').select2({
dataAdapter: CustomDataAdapter
});
});
Example of select2 to handle big array. I am fetching data from server using ajax. Handling searching and pagination locally with more than 20000 data json.
<select id="widget_project"></select>
<script>
$(function () {
allProjects;// having all project json data
pageSize = 50
jQuery.fn.select2.amd.require(["select2/data/array", "select2/utils"],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var results = [];
if(p_term !== "" && typeof params.term === "undefined"){
params.term = p_term;
console.log(params.term);
}
if (params.term && params.term !== '') {
p_term = params.term;
results = findItem(params.term);
} else {
results = allProjects;
}
if (!("page" in params)) {
params.page = 1;
}
var data = {};
data.results = results.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < results.length;
callback(data);
};
$(document).ready(function () {
$("#widget_project").select2({
minimumInputLength: 3,
placeholder:"Select a project",
ajax: {},
dataAdapter: CustomData
});
});
})
});
</script>

Backbone error while posting json

I somehow made basic to-do list, but without ability to save tasks on a server. Now started implementing server side, but having a hard time grasping the whole idea of how is that all supposed to communicate with each other. Here's what I tried to do: in a TodoView (which is rendering the list) I made a model with input value and via save() method tried to post in on a server. As i said I lack grasping a general idea, how is that json supposed to be saved on a server (will it be saved in a tasks.json file which I passed in Collection?). Any help, tips and directions would be greatly appreciated!
Here's my Backbone code
var Model = Backbone.Model.extend({
default: {
task: '',
completed: false
}
});
var Collection = Backbone.Collection.extend({
model: Model,
url: '/tasks.json'
});
var ItemView = Backbone.View.extend({
tagName: 'li',
render: function () {
this.$el.data('cid', this.model.cid);
this.$el.html(this.model.toJSON().task);
return this;
}
});
var TodoView = Backbone.View.extend({
el: '#todo',
initialize: function () {
this.collection = new Collection();
this.collection.on('add', this.render, this);
// this.collection.fetch();
},
events: {
'click .add': 'add',
'dblclick li': 'destroy',
'keydown': 'keyEvent'
},
add: function () {
// this.collection.add(new Model({ //adding input as an model to collection
// task: this.$('#todo').val(),
// completed: false
// }));
var taskData = {
task: this.$('#todo').val(),
completed: false
};
var newlyCreatedModel = new Model({
task: this.$('#todo').val(),
completed: false
});
newlyCreatedModel.save({
// url: '/tasks.json',
data: JSON.stringify(taskData),
type: 'POST',
contentType: 'application/json'
});
this.$('#todo').val(''); //clearing input field
this.$('#todo').focus(); //focusing input after adding task
},
keyEvent: function (e) {
if (e.which === 13) {
this.add();
}
},
destroy: function (e) {
// e.preventDefault();
var id = $(e.target).data('cid');
var model = this.collection.get(id);
model.destroy();
e.target.remove();
},
render: function (newModel) {
var self = this,
todoView;
todoView = new ItemView({
model: newModel
});
self.$('.list').append(todoView.render().el);
return this;
}
});
var trigger = new TodoView();
Here's my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validation</title>
</head>
<body>
<div id="todo">
<label for="todo">Write your task</label>
<input type="text" id='todo'><button class='add'>add</button>
<ul class='list'>
</ul>
</div>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script src="main.js"></script>
</body>
</html>
and finally here's my server written on node.js with help of express.js
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/test'));
server.post('/somepath', function (req, res) {
var bodyStr = '';
req.on('data', function (chunk) {
bodyStr += chunk.toString();
});
req.on('end', function (chunk) {
// res.send(bodyStr);
console.log(bodyStr);
});
});
var server = server.listen(8888);

Why are my jQuery hide events not firing and my Backbone sub view not rendering?

Now Solved - See bottom....
I've got a Backbone list view with a button on it that should show the edit elements.
Neither the jQuery hide() call in the 'showAddEntry' function or the view rendering for 'versionEditView' are doing anything at all. I've stepped right through and I'm not getting any errors. I've even tried manually running methods in the console to see what's going on with hide, but I'm not getting anywhere.
Here's the main view...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
initialize: function () {
this.$addEntryArea = $('#addVersionInfoEntryArea');
this.$addEntryButton = $('#addVersionInfoEntryButton');
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
}
});
return this;
},
showAddEntry: function() {
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.versionInfoEditView.render();
return false;
}
});
return versionInfoEntriesView;
});
And here's the child view...
define(['ministry', 'models/m-version-info', 'text!templates/version-info/edit-version-info- entry.html', 'jquery.custom'],
function (Ministry, VersionInfo, TemplateSource) {
var editVersionInfoView = Ministry.View.extend({
template: Handlebars.compile(TemplateSource),
initialize: function () {
this.$dbVersionInput = this.$('#dbVersion');
this.$tagInput = this.$('#tag');
},
render: function () {
this.$el.html(this.template());
return this;
},
events: {
'submit .edit-version-info-form': 'saveEntry'
},
saveEntry: function() {
var entry = new VersionInfo.Model({ dbVersion: this.$dbVersionInput.val(), tag: this.$tagInput.val() });
entry.save({
success: function() {
alert('Your item has been saved');
}
});
return false;
}
});
return editVersionInfoView;
});
And the main template...
<h2>Version Info</h2>
<div id="info">
<a id="addVersionInfoEntryButton" href="#/versioninfo">Add manual entry</a>
<div id="addVersionInfoEntryArea">
</div>
<ul id="items">
{{#each items}}
<li>{{dbVersion}} | {{tag}}</li>
{{/each}}
</ul>
</div>
And the edit template...
<form class="edit-version-info-form">
<h3>Create a new entry</h3>
<label for="dbVersion">DB Version</label>
<input type="text" id="dbVersion" maxlength="10" />
<label for="tag">Tag</label>
<input type="text" id="tag" />
<button type="submit" id="newEntryButton">Create</button>
</form>
I'm fairly new to backbone so I may well be doing something totally wrong, but I can't see anything wrong with the approach so far and it's not throwing any errors.
OK - Fix as follows after some facepalming...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
$addEntryArea: undefined,
$addEntryButton: undefined,
initialize: function () {
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
that.$addEntryArea = that.$('#addVersionInfoEntryArea');
that.$addEntryButton = that.$('#addVersionInfoEntryButton');
}
});
return this;
},
showAddEntry: function (e) {
e.preventDefault();
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.$addEntryArea.append('Do I want to put it here?');
this.versionInfoEditView.render();
}
});
return versionInfoEntriesView;
});
The issue was due to the fact that I was setting the internal element variables within the view before the completion of the render, so the elements were linked up to nothing. I resolved this by extracting the element initiation to the end of the render success callback.
Here's the fix again...
define(['ministry', 'jquery', 'models/m-version-info', 'views/about/v-edit-version-info-entry', 'text!templates/version-info/version-info.html'],
function(Ministry, $, VersionInfo, VersionInfoEditView, TemplateSource) {
var versionInfoEntriesView = Ministry.View.extend({
el: '#mainAppArea',
template: Handlebars.compile(TemplateSource),
versionInfoEditView: null,
$addEntryArea: undefined,
$addEntryButton: undefined,
initialize: function () {
},
events: {
'click #addVersionInfoEntryButton': 'showAddEntry'
},
render: function () {
var that = this;
var entries = new VersionInfo.Collection();
entries.fetch({
success: function (data) {
that.$el.html(that.template({ items: data.toJSON() }));
that.$addEntryArea = that.$('#addVersionInfoEntryArea');
that.$addEntryButton = that.$('#addVersionInfoEntryButton');
}
});
return this;
},
showAddEntry: function (e) {
e.preventDefault();
if (this.versionInfoEditView != null) {
this.versionInfoEditView.trash();
}
this.versionInfoEditView = new VersionInfoEditView({ el: this.$addEntryArea });
this.$addEntryButton.hide();
this.$addEntryArea.append('Do I want to put it here?');
this.versionInfoEditView.render();
}
});
return versionInfoEntriesView;
});
The issue was due to the fact that I was setting the internal element variables within the view before the completion of the render, so the elements were linked up to nothing. I resolved this by extracting the element initiation to the end of the render success callback.

How can I save a collection, or atleast a portion of it, in backbone.js

I need to maintain the order of models in a collection that are in a model and be able to save it to the server. I know I can save the individual models, but when I save the "parent model" that contains the collection the attribute holding the collection is now saved.
Is there a way to do this? Below is my code. And I know it probably isn't the best, I am still learning.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script type="text/javascript">
$(function() {
var WO = Backbone.Model.extend({
wonum: null,
part: null,
desc: null,
initialize: function()
{
this.url = '/rest/wo/'+this.get('wonum');
}
});
var WOView = Backbone.View.extend({
tagName: "tr",
className: "wo",
initialize: function(options)
{
this.render = _.bind(this.render, this);
},
render: function()
{
$(this.el).html("<td>"+this.model.get('wonum')+"</td><td>"+this.model.get('part')+"</td><td>"+this.model.get('desc')+"</td>");
return this;
}
});
var WOs = Backbone.Collection.extend({
model: WO,
url: '/rest/section/wos/'
});
var Section = Backbone.Model.extend({
defaults: {
name : "Section"
},
wos: [],
url: '/rest/section/',
initialize: function()
{
this.wos = new WOs();
this.wos.url += this.id;
this.url += this.id;
}
});
var SectionView = Backbone.View.extend({
tagName: "table",
initialize: function()
{
_(this).bindAll('add','remove');
var that = this;
this._woViews = [];
this.model.wos.each(this.add);
this.model.wos.bind('add', this.add);
},
add: function(woObj)
{
var wov = new WOView({
model: woObj,
id: woObj.get('wonum')});
this._woViews.push(wov);
if(this._rendered)
$(this.el).append(wov.render().el);
this.model.save();
},
render: function()
{
this._rendered = true;
var that = this;
$(this.el).empty();
$(this.el).append("<thead><th>WO</th><th>Part</th><th>Desc</th></thead>");
$(this.el).append("<tbody>");
_(this._woViews).each(function(wov)
{
$(that.el).append(wov.render().el);
});
$(this.el).append("</tbody>");
return this;
}
});
var sec = new Section({id: 1});
sec.wos.add({
wonum: 1001,
part: 'p1001',
desc: 'd1001'});
sec.wos.add({
wonum: 1002,
part: 'p1002',
desc: 'd1002'});
var secv = new SectionView({model: sec, id: sec.get('id')});
$("body").append(secv.render().el);
$("#addwo").bind("click",function()
{
secv.add(new WO({
wonum: 1005,
part: 'p1005',
desc: 'd1005'}));
});
});
</script>
</head>
<body>
<button id='addwo'>Add WO</button>
</body>
</html>
I would consider using the Collection's comparator function (which you can set) to preserve the order of the collection. This comparator would potentially use a property of the models; so for instance, the model's name or even a position property.
Using this approach, you would just save each model independently, but have the collection potentially refresh itself (where it would use the comparator to preserve the desired order).

Categories

Resources