Why my simple view is not working - backbone.js

I have this JS code:
$(function() {
var LinkView = new Backbone.View.extend({
render: function() {
this.$el.html(this.model.get('text'));
}
});
var Link = Backbone.Model.extend({
text: 'message',
say: function() {
console.log(this.text);
}
});
var l = new Link();
l.say();
var v = new LinkView({model : l, el : 'body'});
v.render();
});
I am waiting to get 'message' on the browser, but get the error TypeError: r.apply is not a function in the console. Why and how can I fix it ?

Please paste this, new was the problem in View, also did slight modification. it works now..
$(function() {
var Link = Backbone.Model.extend({
defaults : {
text: 'default message'
},
say: function() {
console.log(this.get('text'));
}
});
var LinkView = Backbone.View.extend({
render : function() {
this.$el.html(this.model.get('text'));
}
});
var l = new Link({text:'custom text message'});
l.say();
var v = new LinkView({model : l, el : 'body'});
v.render();
});

Related

Marionette, backbone js betting game

This is a betting game, made in backbone. I have a bounty of 100 to help me refactor it into a marionette based application.
I am unsure where to start - in terms of reconfiguring the models, how to swap the views out to make them regions.
I believe the steps would be to start with creating a new marionette application and router.
var app = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
}
});
var app = new app({container: '#app'});
//router
var MyRouter = Marionette.AppRouter.extend({
appRoutes: {
"some/route": "someMethod"
},
routes : {
"some/otherRoute" : "someOtherMethod"
},
someOtherMethod : function(){
// do something here.
}
});
Then create a few regions and layouts to manage old backbone views.
//regions
MyApp.addRegions({
bankValue: "#bankvalue",
bitValue: "#bitvalue"
});
Then convert the old backbone views to Marionette's ItemViews and CompositeViews.
//compositeview
var CompositeView = Marionette.CompositeView.extend({
template: "#personalbank"
});
new CompositeView({
model: userModel,
collection: someCollection
});
Here is the latest js fiddle.
//UserBankModel
var UserBankModel = Backbone.Model.extend({
defaults: {
chips: 200
},
initialize: function() {
console.log("UserBankModel initialize");
this.on("change:chips", function(model) {
var chips = model.get("chips"); // 23232
console.log("Changed my chips to " + chips);
});
}
});
//UserBankView
var UserBankView = Backbone.View.extend({
initialize: function() {
console.log("UserBankView initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//BitcoinModel
var BitcoinModel = Backbone.Model.extend({
defaults: {
currentValue: 0,
lockedValue: 0
},
initialize: function() {
console.log("BitcoinModel initialize");
this.on("change:currentValue", function(model) {
var currentValue = model.get("currentValue"); // 494
console.log("Changed my currentValue to " + currentValue);
});
},
getBitcoinValue: function(callback) {
/*
Backbone.ajax({
dataType: 'json',
url: "https://api.bitcoinaverage.com/ticker/USD",
crossDomain: true,
success: function(data) {
callback(data);
}
});
*/
json= {
bid: 320,
ask: 444
};
var mediumValue = (json.bid + json.ask) / 2;
callback(mediumValue);
}
});
//BitcoinView
var BitcoinView = Backbone.View.extend({
initialize: function() {
console.log("BitcoinView initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
var App = Backbone.Model.extend({
initialize: function() {
var that = this;
this.userBankModel = new UserBankModel();
this.userBankView = new UserBankView({
el: $("#bankvalue")
});
this.bitcoinModel = new BitcoinModel();
this.bitcoinView = new BitcoinView({
el: $("#bitvalue")
});
//setInterval(function() {
//get val of bitcoin every second
that.bitcoinModel.getBitcoinValue(function(mediumVal) {
//set bit coin model
that.bitcoinModel.set({
currentValue: mediumVal
});
//render the bit coin value
that.bitcoinView.render(that.bitcoinModel.get("currentValue"));
});
//}, 1000);
//render users chips
this.userBankView.render(this.userBankModel.get("chips"));
},
currentBitcoinValue: 0,
startBet: function(state) {
console.log("start timer");
this.state = state;
//get locked value of bitcoin for the game
var stashValue = this.bitcoinModel.get("currentValue");
//set bit coin model with locked value
this.bitcoinModel.set({
lockedValue: stashValue
});
var initialTimer = 5;
var Timer = {
i: initialTimer,
onTimer: function() {
var that = this;
document.getElementById('timer').innerHTML = Timer.i;
Timer.i--;
if (Timer.i < 0) {
app.gameResult();
Timer.i = initialTimer; //reset
} else {
setTimeout(Timer.onTimer, 1000);
}
}
};
Timer.onTimer();
},
gameResult: function() {
console.log("whats the result then");
console.log("this.state", this.state);
var lockedValue = this.bitcoinModel.get("lockedValue");
var currentValue = this.bitcoinModel.get("currentValue");
console.log("lockedValue>>", lockedValue);
console.log("currentValue>>", currentValue);
var result = "loss";//lose by default
//locked value was higher
if (
this.lockedValue > this.currentValue && this.state["bet"] == "high" ||
this.lockedValue < this.currentValue && this.state["bet"] == "low"
) {
result = "win";//win if conditions are met
}
//get current value of user chips
var newVal = this.userBankModel.get("chips");
if (result == "win") {
console.log("WIN -- you get chips");
newVal += this.state["wager"];
} else {
console.log("LOSS -- you loose chips");
newVal -= this.state["wager"];
}
//won or lost chips -- set new chip value
this.userBankModel.set({
chips: newVal
});
//render new user chips
this.userBankView.render(this.userBankModel.get("chips"));
}
});
var app = new App();
var FormView = Backbone.View.extend({
el: '#wager-form',
events: {
"submit": "doMethod"
},
doMethod: function(e) {
e.preventDefault();
var obj = [];
this.$el.find('input[name]').each(function() {
obj[this.name] = this.value;
});
//start bet
app.startBet(obj);
}
});
var form = new FormView();
I would like to know more about the best practice in using Marionette with backbone. Why use Marionette, what is the advantage?
Is it a simple case of refactoring the following example. Or does a Marionette based method work more like a collection?
var App = Backbone.Model.extend({
initialize: function() {
//standard app
}
});
But would this be the way to refactor the App model to use Marionette?
var App = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
//invoke other models
this.otherModel1 = new OtherModel1();
this.otherView1= new OtherView1({
el: $("#selector1")
});
}
});
//add the selectors in one place?
MyApp.addRegions({
someRegion: "#some-div",
anotherRegion: "#another-div"
});
// Although applications will not do anything
// with a `container` option out-of-the-box, you
// could build an Application Class that does use
// such an option.
var app = new App({container: '#app'});
This is the structure of my application. How would I refactor it properly to use marionette
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>backbone js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.4/backbone.marionette.js"></script>
</head>
<body>
Content of the document......
<div id="app"></div>
<div id="select1"></div>
<div id="select2"></div>
<script>
//myModel1
var MyModel1 = Backbone.Model.extend({
initialize: function() {
console.log("myModel1 initialize");
}
});
//myView1
var MyView1 = Backbone.View.extend({
initialize: function() {
console.log("myView1 initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//myModel2
var MyModel2 = Backbone.Model.extend({
initialize: function() {
console.log("myModel2 initialize");
}
});
//myView2
var MyView2 = Backbone.View.extend({
initialize: function() {
console.log("myView2 initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//the core that invokes and bridges the other models.
var App = Backbone.Model.extend({
initialize: function() {
var that = this;
this.myModel1 = new MyModel1();
this.myView1 = new MyView1({
el: $("#select1")
});
this.myModel2 = new MyModel2();
this.myView2 = new MyView2({
el: $("#select2")
});
}
});
var app = new App();
/*ok marionette stuff*/
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log(options.container);
}
});
var myApp = new MyApp({container: '#app'});
</script>
</body>
</html>
Ok so would the code kind of look like this? Where I pump the models into the options variable?
MyApp.addInitializer(function(options){
// do useful stuff here
var otherView1= new OtherView1({
model: options.otherModel1
});
MyApp.mainRegion.show(otherView1);
});
MyApp.addInitializer(function(options){
new MyAppRouter();
Backbone.history.start();
});
this is my current application - but I am unsure how to structure it with marionette moving forward?
Latest fiddle of the entire core application.
Ok so, I have my application with standard backbone like this..
with a core Model that invokes and bridges the other models. Something like this.
Old backbone way
var App = Backbone.Model.extend({
initialize: function() {
this.myModel1 = new MyModel1();
this.myView1 = new MyView1({
el: $("#select"),
model: this.myModel1
});
this.myModel2 = new MyModel2();
this.myView2 = new MyView2({
el: $("#select"),
model: this.myModel2
});
}
});
so is Marionette supposed to work like this?
App.addInitializer(function(options) {
App.myModel1 = new MyModel1();
App.myView1 = new MyView1({
el: $("#select1"),
model: App.myModel1
});
App.myModel2 = new MyModel2();
App.myView2 = new MyView2({
el: $("#select2"),
model: App.myModel2
});
});
and what about regions.. Do I stop using el: selectors for the view and rely on regions? And if so, how?
var View1Region = Backbone.Marionette.Region.extend({
el: "#select1", // Must be defined for this syntax
// Whatever other custom stuff you want
});
var View2Region = Backbone.Marionette.Region.extend({
el: "#select2", // Must be defined for this syntax
// Whatever other custom stuff you want
});
// Use these new Region types on App.
App.addRegions({
view1Region: View1Region,
view2Region: View2Region
});
// This is equivalent to:
App.view1Region = new View1Region();
App.view2Region = new View2Region();
I've made a new jsfiddle to start structuring the marionette version.
but am I invoking it correctly, using the new composite view correctly.
//UserBankModel
var UserBankModel = Backbone.Model.extend({
defaults: {
chips: 200
},
initialize: function() {
console.log("UserBankModel initialize");
this.on("change:chips", function(model) {
var chips = model.get("chips"); // 23232
console.log("Changed my chips to " + chips);
});
}
});
var CompositeView = Marionette.CompositeView.extend({
template: "#personalbank"
});
var userBankView = new CompositeView({
model: UserBankModel
});
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
this.userBankModel = new UserBankModel();
}
});
var app = new MyApp({
container: '#app'
});
app.addRegions({
bankValue: "#bankvalue",
bitValue: "#bitvalue"
});
If we focus on the view for a second, how would I refactor this in the way I was intending to.
html
<div id="list"></div>
<script type="text/template" id="list-template">
<div class="pagination">
<ul></ul>
</div>
</script>
<script type="text/template" id="item-template">
<%= id %>
</script>
js
var Item = Backbone.Model.extend();
var Items = Backbone.Collection.extend({
model: Item
});
var Views = {};
Views.ListItem = Backbone.Marionette.ItemView.extend({
template: "#item-template",
tagName: 'li'
});
Views.List = Backbone.Marionette.CompositeView.extend({
template: "#list-template",
itemView: Views.ListItem,
itemViewContainer: "ul"
});
var Data = [
{id: 1},
{id: 2}
];
var items = new Items(Data);
var list = new Views.List({
collection: items
});
list.render();
$("#list").html(list.el);
http://jsfiddle.net/c72Vg/168/
A while ago the answer would have been "no", use Marionette's Application.addInitializer(function () {}) but when Marionette v3 is released that will be removed and in it's place you're expected to use events.

backbone Cannot read property 'push' of undefined

i'm working with Backbone and when I generate the view I have the error Cannot read property 'push' of undefined". The line of the error is "self.subViewsReservas.push(new ReservaView({" in the push.
ReservaCollectionView = Backbone.View.extend({
initialize: function () {
if (Session.get('authenticated') && Session.get('authenticated') !== false) {
this.paginacionVista = new PaginacionReservasView({
collection: this.collection,
el: '.paginacionReservas',
reservasPagina: 5,
});
this.buscadorVista = new BuscadorView({
el: 'div.buscador-reservas',
//Pasamos la colección oficinas ya que hará las veces del conjunto de oficinas retornadas por el servidor
collection: new OficinasCollection(oficinas),
});
}
else {
}
},
render: function () {
var self = this;
this.template = _.template($('#divReservaTpl').html(), {});
self.$('.contenedor-reservas').empty();
self.collection.each(function (reserva, index) {
self.$('.contenedor-reservas').append(self.template({'data': reserva.toJSON()}));
});
this.collection.each(function (reserva, index) {
this.subViewsReservas = [];
self.subViewsReservas.push(new ReservaView({
el: '#' + reserva.get('Idreserva'),
model: reserva
}));
});
this.collection.each(function (reserva, index) {
//Limite de la paginacion 5 limite arbitrario
if (index < 5) {
//Lo Marcamos como visible y actualiazamos la paginación
self.collection.get(reserva.get('Idreserva')).set({'Visibilidad': true});
}
});
this.paginacionVista.render();
return this;
},
});
AppView = Backbone.View.extend({
initialize : function(){
var self = this;
self.usu = new UsuarioModel();
self.usu.fetch({
success: function (model){
Session.fetch({
success : function (){
Session.set('nombre',model.get('Nombre'));
Session.set('apellidos',model.get('Apellidos'));
Session.set('puntos_club',model.get('Puntosclub'));
self.render();
}
});
self.sideBar = new SideBarView({
el : '.sidebar',
model: model
});
self.sideBar.markOption('mis-reservas');
AppView = Backbone.View.extend({
initialize : function(){
var self = this;
self.usu = new UsuarioModel();
self.usu.fetch({
success: function (model){
Session.fetch({
success : function (){
Session.set('nombre',model.get('Nombre'));
Session.set('apellidos',model.get('Apellidos'));
Session.set('puntos_club',model.get('Puntosclub'));
self.render();
}
});
self.sideBar = new SideBarView({
el : '.sidebar',
model: model
});
self.sideBar.markOption('mis-reservas');
},
error : function (){
document.location = '/mygoldcar/login';
}
});
this.listenTo(Session, 'change', self.update);
},
render : function(){
var self = this;
var reservas = new ReservasCollection();
reservas.fetch({
success: function (collection){
if ( typeof collection.models[0].get('error') == 'undefined' || !collection.models[0].get('error')) {
var listRes = new ReservaCollectionView({
el : '.reservas-list',
collection: collection
});
listRes.render();
var popoverModel = new Popover();
popoverModel.setData(collection.models[0].get('kilometraje_ilimitado'), collection.models[0].get('duracion'));
self.popover = new PopoverView({
el: 'body',
model: popoverModel
});
self.popover.establecerPopover();
}
else document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1';
},
error: function () {
document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1';
}
});
},
update: function() {
var self = this;
self.sideBar.update(Session.get('nombre'),Session.get('apellidos'),Session.get('puntos_club'));
self.$el.find('.nombre-usuario').text(Session.get('nombre'));
},
updatePoints: function() {
var self = this;
self.usu.fetch({
success: function (model){
Session.set('puntos_club',model.get('Puntosclub'));
}
});
}
}); },
error : function (){
document.location = '/mygoldcar/login';
}
});
this.listenTo(Session, 'change', self.update);
},
render : function(){
var self = this;
var reservas = new ReservasCollection();
reservas.fetch({
success: function (collection){
if ( typeof collection.models[0].get('error') == 'undefined' || !collection.models[0].get('error')) {
var listRes = new ReservaCollectionView({
el : '.reservas-list',
collection: collection
});
listRes.render();
var popoverModel = new Popover();
popoverModel.setData(collection.models[0].get('kilometraje_ilimitado'), collection.models[0].get('duracion'));
self.popover = new PopoverView({
el: 'body',
model: popoverModel
});
self.popover.establecerPopover();
}
else document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1';
},
error: function () {
document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1';
}
});
},
update: function() {
var self = this;
self.sideBar.update(Session.get('nombre'),Session.get('apellidos'),Session.get('puntos_club'));
self.$el.find('.nombre-usuario').text(Session.get('nombre'));
},
updatePoints: function() {
var self = this;
self.usu.fetch({
success: function (model){
Session.set('puntos_club',model.get('Puntosclub'));
}
});
}
});
Inside collection.each, this points to the collection. So the property subViewsReservas is added to it, not the view instance. When you try to access it like self.subViewsReservas.push, self points to the view instance, which doesn't have subViewsReservas property, hence the error.
Initializing an array inside each like you're doing isn't doing much since it'll be reset with each invocation of the callback.
You should be initializing it in the initialize method, which is the right place to initialize things, where this will correctly point to the view instance as shown below
initialize: function () {
this.subViewsReservas = [];
}
For some reason if you want the collection to reset everytime, you can change the context to view by passing it as second argument to each like:
this.collection.each(function (reserva, index) {
this.subViewsReservas = [];
self.subViewsReservas.push(new ReservaView({
el: '#' + reserva.get('Idreserva'),
model: reserva
}));
}, self); // <--- makes view the context of callback,
// both 'self' and 'this' will refer to view

$el.append not working in backbone.js

console.log('Loaded inedx.js-->');
console.log(jQuery);
(function($){
console.log('In immediate block');
//Create new tweet view
var Tweet = Backbone.Model.extend({
defaults: function(){
return {
name : 'defaultName',
status : 'default status'
}
}
});
var TweetList = Backbone.Collection.extend({
model :Tweet
});
var TweetView = Backbone.View.extend({
model : new Tweet(),
tagName : 'div',
initialize : function(){
this.template = _.template($('#tweet-template').html());
},
render : function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var tweets = new TweetList();
var TweetsView = Backbone.View.extend({
model : tweets,
tagName : 'div',
el : $('#allTweetContainer'),
initialize: function(){
this.model.on('add',this.render,this);
},
render : function(){
var self = this;
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().$el.html());
});
return this;
}
});
$(document).ready(function (){
tweets.add(new Tweet({
status : 'status1',
author : 'author1'
}));
var tweet = new Tweet({
status : 'status1-----',
author : 'author1-------'
});
//console.log(new TweetView());
//$('#allTweetContainer').append( _.template($('#tweet-template').html(),tweet.toJSON()));
tweets.add(new Tweet({
status : 'status2',
author : 'author2'
}));
tweets.add(new Tweet({
status : 'status3',
author : 'author3'
}));
tweets.add(new Tweet({
status : 'status4',
author : 'author4'
}));
var tweetApp = new TweetsView();
tweetApp.render();
console.log(tweets.toJSON());
});
})(jQuery);
I am not able to render TweetsView.
Instead of : self.$el.append
When I used : `$('#allTweetContainer').append
it worked. But ideally it should work with self.$el.append.
I believe there must be something extra needs to be done to get proper $el which should be a jQuery variable pointing to the given el.
Any pointers would really helpful. Thanks in advance.
You should declare el as string and not as jQuery selector. So your TweetsView should look like this:
var TweetsView = Backbone.View.extend({
model : tweets,
tagName : 'div',
el : '#allTweetContainer',
initialize: function(){
this.model.on('add',this.render,this);
},
render : function(){
var self = this;
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().$el.html());
});
return this;
}
});
when appending the TweetView to TweetsView, you could also do this:
_.each(this.model.toArray(),function(tweet,i){
self.$el.append((new TweetView({model:tweet})).render().el);
});

Controller listenTo breaks when in callback method

I have the problem that the event "form:selectedForm" is calling the method "showForm" but when sending this to my view I am getting the following error: TypeError: e[t] is not a function.
This is stated in line 128 in the backbone.js script but I have no clue what he is doing there. It looks like that he is looking for a "to" or "on" event on the collection.
What I am doing wrong here?
MyController = Backbone.Marionette.Controller.extend({
initialize: function(options) {
this.options = options;
this.urls = options.urls;
this.mainRegion = options.mainRegion;
this.view = new MyLayout();
this.mainRegion.show(this.view);
this.view.render();
this.showSelectorView(this.view.formHeader);
},
showSelectorView : function(view) {
var forms = new MyForms();
forms = this.urls.loadForms;
var selectorView = new FormSelectorView({
collection: forms
});
forms.fetch();
this.listenTo(selectorView, "form:selectedForm", this.showForm);
view.show(selectorView);
},
showForm : function(models) {
console.log("showForm");
var form = new FormContentView({
collection: models
});
this.view.form.show(form);
}
});
MyLayout = Backbone.Marionette.Layout.extend({
template: Backbone.Marionette.TemplateCache.get('#content'),
regions: {
formHeader: "#selector",
form: "#formContent",
formContent: "#content",
formFooter: "#save",
formTemplates: "#templates"
}
});
FormSelectorView = Backbone.Marionette.ItemView.extend({
template: Backbone.Marionette.TemplateCache.get('form-selector-template'),
events : {
"click option" : "selectForm"
},
initialize : function() {
this.listenTo(this.collection, "sync", this.render, this);
},
selectForm : function(e) {
e.preventDefault();
var id = $(e.currentTarget).attr("name");
var item = this.collection.get(id);
this.trigger("form:selectedForm", item.attributes.fields);
}
});
I think the error is in your showSelector view function, you are overwriting your forms collection in the second line,
i think your intention in that line was to assing the url of the forms collection so my guess is that this will fix it:
showSelectorView : function(view) {
var forms = new MyForms();
forms.url = this.urls.loadForms; /// Im assuming you were trying to pass the url here
var selectorView = new FormSelectorView({
collection: forms
});
forms.fetch();
this.listenTo(selectorView, "form:selectedForm", this.showForm);
view.show(selectorView);
},

Save the model from view?

I am developing a Backbone web application and I want to know that how can post data from the view
This is my Model:
App.Models.edit = Backbone.Model.extend({
defaults : {
id : undefined,
fname : undefined,
lname : undefined,
phone : undefined,
address : undefined,
email : undefined,
url: undefined,
},
initialize: function(){
this.set({url : '../api/getOne/' + App.CurrentID });
},
getAttrs: function(attr){
return this.get(attr);
}
});
And this is my view:
App.Views.edit = Backbone.View.extend({
el: $("#modal"),
initialize: function(){
App.TplNames.edit = $('body');
App.Tpls.edit('edit');
this.model.bind("reset", this.render, this);
this.render();
},
events: {
'click .btnSave': 'saveDetails',
},
saveDetails: function(){
this.model.save();
//console.log(this.model);
},
render: function(){
var elem = '';
$.each(this.model.models, function(i, k){
var template = _.template( $('#tpl_edit').html(), k.toJSON() );
elem += template;
});
$(this.el).html(elem);
$("#myModal").modal('show');
$("#myModal").on('hidden', function(){
//alert(123);
document.location.href = App.Url + '#view';
});
var attrs = "";
$.each(this.model.models, function(i, k){
attrs = k.toJSON();
});
$("#fname").val(attrs.fname);
$("#lname").val(attrs.lname);
$("#Email").val(attrs.email);
$("#Phone").val(attrs.phone);
$("#Address").val(attrs.address);
//console.log(attrs);
}
});
And it is my Router
App.Router = Backbone.Router.extend({
routes: {
"" : "def",
"home" : "def",
"view" : "getAll",
"edit/:id" : "edit",
"add" : "addContact",
},
def: function(){
this.mainModel = new App.Collections.Main();
this.mainView = new App.Views.Main({model: this.mainModel});
//this.mainModel.fetch();
},
edit: function(id){
App.CurrentID = id;
var contactCollObj = new App.Collections.edit();
viewObj = new App.Views.edit({model: contactCollObj});
contactCollObj.fetch();
viewObj.render();
//console.log(contactCollObj);
},
getAll: function(){
//alert(123);
var collObj = new App.Collections.View();
var viewObj = new App.Views.View({model: collObj});
collObj.fetch();
},
addContact: function(){
//var model = new App.Collections.AddContact();
model = new App.Models.AddContact();
var view = new App.Views.AddContact({model: model});
//view.render();
}
});
var app = new App.Router();
Backbone.history.start();
And when I want to save the model, It generates an error:
this.model.save is not a function
Every thing is okay except the above...
In your router you pass collection to App.Collections.edit view as model:
var contactCollObj = new App.Collections.edit();
viewObj = new App.Views.edit({model: contactCollObj});
That is why you cannot call save(). save() is only available for a model not a collection.
You probably want to initialize view with collection
viewObj = new App.Views.edit({collection: contactCollObj});
And then also modify some of your view code accordingly.

Resources