Calling view function from another view from autocomplete - backbone.js

I have the following views in my application.
sets.js
define([
'jquery',
'underscore',
'backbone',
'bootstrap',
'jqueryui',
'numberformat',
'text!templates/sets/sets.html'
], function ($, _, Backbone, bootstrap, jqueryui, numberformat, setsTemplate) {
var setsView = Backbone.View.extend({
el: $("#contenido"),
events: {
'keyup table tbody input': 'afterRender'
},
initialize: function (options) {
_.bindAll(this, 'render', 'afterRender');
this.options = options || {};
},
render: function () {
var data = {sets: this.options.sets};
var compiledTemplate = _.template(setsTemplate, data);
this.$el.html(compiledTemplate);
$(".alert").addClass('alert-' + this.options.clase);
var tabs = $("#tabs").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
}
});
$('#emisor').hide();
this.afterRender();
},
afterRender: function () {
console.log('afterRender');
var ventasView = new VentasView();
ventasView.render();
}
})
return setsView;
});
ventas.js
define([
'jquery',
'underscore',
'backbone',
'bootstrap',
'jqueryui',
'text!templates/cliente/cliente.html',
'models/cliente',
'views/sets/sets'
], function ($, _, Backbone, bootstrap, jqueryui, clienteTemplate, SetsView) {
var clienteView = Backbone.View.extend({
el: $("#cliente"),
initialize: function (options) {
this.options = options || {};
},
render: function () {
$("#cliente").html(clienteTemplate);
$('#rut').autocomplete(
{
source: '/clientes/buscar/',
minLength: 1,
dataType: 'json',
cache: false,
select: function (event, ui) {
$("#rut").val(ui.item.Cliente.rut);
$("#id").val(ui.item.Cliente.id);
$("#razon").val(ui.item.Cliente.razon);
$("#giro").val(ui.item.Cliente.giro);
$("#direccion").val(ui.item.Cliente.direccion);
$("#comuna").val(ui.item.Cliente.comuna);
$("#ciudad").val(ui.item.Cliente.ciudad);
var sets = new SetsView();
sets.afterRender();
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.Cliente.rut + "</strong></a>").appendTo(ul);
};
}
});
return clienteView;
});
error
Uncaught TypeError: Object [object Object] has no method 'afterRender'

You are missing a parameter in your function :
function ($, _, Backbone, bootstrap, jqueryui, clienteTemplate, SetsView)
function ($, _, Backbone, bootstrap, jqueryui, clienteTemplate, clienteModel, SetsView)

Related

Cannot read property 'replace' of undefined BackboneJS

I am trying to render a View(customerEditView) using modular BackboneJS but it gives me the uncaught type error.
this is my router.js file:
define([
'jquery',
'underscore',
'backbone',
'views/Customers/CustomerEditView',
'views/Customers/CustomerListView'
], function($, _, Backbone, CustomerEditView, CustomerListView) {
var Router = Backbone.Router.extend({
routes: {
"customers": "customerhome",
"editcustomer/:id": "editcustomer",
"newcustomer": "editcustomer",
},
customerhome: function () {
var customerListView = new CustomerListView();
customerListView.render();
},
editcustomer: function (id) {
var customerEditView = new CustomerEditView();
customerEditView.render({ id: id });
}
});
var initialize = function () {
var router = new Router;
Backbone.history.start();
};
return {
initialize: initialize
};
});
and this is my customerEditView file:
define([
'jquery',
'underscore',
'backbone',
'router',
'models/Customers/Customer',
'helper/Serialize',
'text!template/Customer/CustomerEditTemplate.html'
], function ($, _, Backbone, router, Customer, Router, serializeObject, CustomerEditTemplate) {
var CustomerEditView = Backbone.View.extend({
el: '.page',
events: {
'submit .edit-customer-form': 'saveCustomer',
'click .delete': 'deleteCustomer'
},
saveCustomer: function (ev) {
var customerDetails = $(ev.currentTarget).serializeObject();
var customer = new Customer();
customer.save(customerDetails, {
success: function (customer) {
Backbone.history.navigate('', { trigger: true });
}
});
return false;
},
deleteCustomer: function (ev) {
this.customer.destroy({
success: function () {
console.log('destroyed');
Backbone.history.navigate('', { trigger: true });
}
});
return false;
},
render: function (options) {
var that = this;
if (options.id) {
that.customer = new Customer({ id: options.id });
that.customer.fetch({
success: function (customer) {
var template = _.template(CustomerEditTemplate);
that.$el.html(template({ customer: customer }));
}
});
} else {
var template = _.template(CustomerEditTemplate);
that.$el.html(template({ customer: null }));
}
}
});
return CustomerEditView;
});

Backbone.history.start() in ie8 leads to page reload every 20 seconds

Simple application-pilot with Backbone + requireJs.
In ie8 string Backbone.history.start({pushState: true}); leads to page reload every 20 seconds. Without it application doesnt start. What is the problem?
Below content of router.js :
define(
[
'jquery', 'underscore',
'backbone'
],
function ($, _, Backbone) {
var MainRouter = Backbone.Router.extend({
initialize: function () {
var re = new RegExp("(\/)+$", "g");
this.route(/(.*)\/+$/, "trailFix", function (id) {
// remove all trailing slashes if more than one
id = id.replace(re, '');
this.navigate(id, true);
});
},
routes: {
'home': 'showMainPage'
},
showMainPage: function (param) {
require([ 'views/global/main'], function (MainView) {
$(".navigation_item[data-type=home]").addClass("selected").on('click', function () {
return false;
})
$(".p_map, .p_feed").show();
new MainView();
});
}
});
var initialize = function () {
window.mainRouter = new MainRouter();
Backbone.history.start({pushState: true});
};
return {
initialize: initialize
};
});
This is fix for IE8
Backbone.history.loadUrl(window.location.pathname);

backbone-extend.js doesn't seem to load my method

I added this to my backbone-extend.js file which resides in the same folder as backbone-min.js...
_.extend(Backbone.View.prototype, {
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
});
However, when I call this.getFormData in my view code, I get a method not defined error. What am I missing? Thanks for your help!
Edit: Here is my view. I have to uncomment the getFormData method to make it work. It can't see the getFormData otherwise...
define([
'jquery',
'underscore',
'backbone',
'models/Member',
'text!templates/memberEditTemplate.html'
], function($, _, Backbone, Member, memberEditTemplate) {
var MemberEditView = Backbone.View.extend({
el: $("#page"),
model: 'member',
initialize: function(args) {
this.member = new Member({ id: args.id });
this.member.on('error', this.eventSyncError, this);
this.member.on('sync', this.eventSyncModelLoaded, this);
this.member.fetch();
},
events: {
"click #bttnMemberSave": "bttnClickMemberSave"
},
eventSyncError: function(model,response,options) {
console.log('Sync error='+response.statusText);
$('#server-message').css({'color':'red', 'font-weight':'bold'}).text(response.statusText);
//$('#server-message').text(response.statusText);
},
eventSyncModelLoaded: function(model,response,options) {
this.render();
},
eventSyncModelSaved: function(model,response,options) {
console.log("Member saved!");
$('#server-message').css({'color':'green', 'font-weight':'bold'}).text("Member saved!");
//$('#server-message').text('Member saved!');
var to = setTimeout(function() { Backbone.history.navigate('members', true); }, 2000);
},
bttnClickMemberSave: function() {
var data = this.getFormData($('#member-form').find('form'));
this.member.save(data, { success: this.eventSyncModelSaved });
},
// getFormData: function(form) {
// var unindexed_array = form.serializeArray();
// var indexed_array = {};
// $.map(unindexed_array, function(n, i){
// indexed_array[n['name']] = n['value'];
// });
// return indexed_array;
// },
render: function() {
this.member.toJSON();
var compiledTemplate = _.template( memberEditTemplate, { member: this.member } );
this.$el.html( compiledTemplate );
return this;
}
});
return MemberEditView;
});
Ok, I added backbone-extend.js to the RequireJS required files array in my app.js, now it's working.

uncaught typeerror: object function has no method 'tojson'

I have created a model like this
define(['backbone', 'text_dictionary'], function(Backbone, Text_Dict) {
var IndexPageModel = Backbone.Model.extend({
defaults:{
val_btn_gotohomepage : Text_Dict.val_btn_gotohomepage,
val_btn_gotologinpage : Text_Dict.val_btn_gotologinpage,
val_btn_gotolistpage : Text_Dict.val_btn_gotolistpage
}
});
return IndexPageModel;
});
and instantiated this model with 'new' in my page code like this
define([ 'page_layout',
'panel_itemview',
'header_itemview',
'content_itemview',
'footer_itemview',
'templates',
'text_dictionary',
'indexpage_model',
'indexpage_logic'],
function( Page,
Panel,
Header,
Content,
Footer,
Templates,
Text_Dict,
IndexPageModel,
IndexPage_BusnLogic) {
console.log("Success..Inside Index Page.");
var Page_Index = {};
Page_Index.page = (function(){
var _pageName = Text_Dict.indexpage_name;
var _pageModel = new IndexPageModel();
return _pageLayout = Page.pageLayout({
name:_pageName,
panelView: Panel.panelView({name:_pageName, pagetemplate: Templates.simple_panel}),
headerView: Header.headerView({name:_pageName, title: Text_Dict.indexpage_header, pagetemplate: Templates.header_with_buttons}),
contentView: Content.contentView({name:_pageName, page_model:_pageModel, pagetemplate:Templates.content_index, busn_logic:IndexPage_BusnLogic.HandleEvents}),
footerView: Footer.footerView({name:_pageName, title: Text_Dict.indexpage_footer, pagetemplate: Templates.simple_footer})
});
})();
return Page_Index;
});
my page gets created using the page layout
define([ 'underscore', 'marionette' ], function( _, Marionette ) {
console.log("Success..Inside Index View.");
var Page = {};
var _ReplaceWithRegion = Marionette.Region.extend({
open: function(view){
//Need this to keep Panel/Header/Content/Footer at the same level for panel to work properly
this.$el.replaceWith(view.el);
}
});
Page.pageLayout = function (opts) {
var _opts = _.extend ({ name: 'noname',
panelView: null,
headerView: null,
contentView: null,
footerView: null,
}, opts);
return new ( Marionette.Layout.extend({
tagName: 'section',
attributes: function() {
return {
'id': 'page_' + _opts.name,
'data-url': 'page_' + _opts.name,
'data-role': 'page',
'data-theme': 'a'
};
},
template: function () {
return "<div region_id='panel'/><div region_id='header'/><div region_id='content'/><div region_id='footer'/>";
},
regions: {
panel: {selector: "[region_id=panel]", regionType: _ReplaceWithRegion},
header: {selector: "[region_id=header]", regionType: _ReplaceWithRegion},
content: {selector: "[region_id=content]", regionType: _ReplaceWithRegion},
footer: {selector: "[region_id=footer]", regionType: _ReplaceWithRegion},
},
initialize: function(){
$('body').append(this.$el);
this.render();
},
onRender: function() {
if (this.options.panelView) {
this.panel.show (this.options.panelView);
};
if (this.options.headerView) {
this.header.show (this.options.headerView);
};
if (this.options.contentView) {
this.content.show(this.options.contentView);
};
if (this.options.footerView) {
this.footer.show (this.options.footerView);
};
},
}))(_opts);
};
return Page;
});
but in my itemview when i am passing model reference like this
define([ 'underscore', 'marionette', 'event_dictionary', 'app' ], function(_,
Marionette, Event_Dict, App) {
console.log("Success..Inside Content Index View.");
var Content = {};
Content.contentView = function(opts) {
return new (Marionette.ItemView.extend({
tagName : 'div',
attributes : function() {
console.log('options name==' + opts.name);
console.log("page model=="+opts.page_model);
return {
'region_id' : 'content',
'id' : 'content_' + opts.name,
'data-role' : 'content'
};
},
initialize : function() {
_.bindAll(this, "template");
},
template : function() {
return opts.pagetemplate;
},
model : function() {
return opts.page_model;
}
}))(opts);
};
return Content;
});
It's giving me error
Uncaught TypeError: Object function () {
return opts.page_model;
} has no method 'toJSON'
The model property of a view cannot be a function. Backbone allows this for some things like url (by way of the _.result helper function), but not in this case. Change your view code to not have a model function and just do this in initialize:
initialize: function (options) {
this.model = this.page_model = options.page_model;
}
UPDATE since you won't just take my word for it, here is the Marionette source that is almost certainly the top of your exception stack trace. Once again: view.model has to be a model object not a function. Fix that and the error will go away.
The accepted answer is correct, but it took a bit of messing about to find out why I had that error coming up, so I'm offering what the solution for my personal use-case was in case it helps anyone else stumbling upon this page in the future.
I had this:
app.module 'Widget.Meta', (Meta, app, Backbone, Marionette, $, _) ->
Meta.metaView = Backbone.Marionette.ItemView.extend
model: app.Entities.Models.meta
template: '#meta-template'
... when I should have had this:
app.module 'Widget.Meta', (Meta, app, Backbone, Marionette, $, _) ->
Meta.metaView = Backbone.Marionette.ItemView.extend
model: new app.Entities.Models.meta()
template: '#meta-template'
It's just a matter of instantiating the function definition.

Handeling response from backbone.js collection using fetch

am pretty new to backbone.js and managed recently to finish my first application. I made a collection that is responsible for fetching data through a API but am not able to loop through the result and use it.
Here is my model file
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var VehicleLookupModel = Backbone.Model.extend({
//data will contain one of the items returned from the collection's 'parse' function.
parse: function(data){
return data;
}
})
return VehicleLookupModel;
});
collection file
define([
'jquery',
'underscore',
'backbone',
'l/models/VehicleLookupModel'
], function($, _, Backbone, VehicleLookupModel){
var VehicleLookupModelSet = Backbone.Collection.extend({
model : VehicleLookupModel,
url : function() {
return '/en/car/api/model-lookup-model.json/'+this.make+'/';
},
parse : function(response) {
return response;
},
initialize: function(options) {
options || (options = {});
this.make = options.make;
}
})
return VehicleLookupModelSet;
});
and finally the view file
define([
'jquery',
'underscore',
'backbone',
'l/collections/VehicleLookupMakeSet',
'l/collections/VehicleLookupModelSet',
'l/collections/VehicleLookupTrimSet'
], function($, _, Backbone, VehicleLookupMakeSet, VehicleLookupModelSet, VehicleLookupTrimSet){
var BrowseVehicleView = Backbone.View.extend({
el: $('#vehicle-browse-form'),
initialize: function(){
// Extend JQuery example
// This would extend JQuery function for resetting elements on the form
$.fn.extend({
resetElement: function(){
$(this).attr('disabled', 'disabled');
$(this).html('');
return $(this);
}
});
// define array of elements to be used in DOM manipulations
this.elements = {
"make" : $('#id_make', this.el),
"model" : $('#id_model', this.el),
"trim" : $('#id_trim', this.el),
"year" : $('#id_year', this.el)
}
},
events: {
"change #id_make" : "onMakeChange",
"change #id_model" : "onModelChange",
"change #id_trim" : "onTrimChange"
},
render: function(){
// Using Underscore we can compile our template with data
},
onMakeChange: function(event) {
this.elements.model.resetElement();
this.elements.trim.resetElement();
this.collection = new VehicleLookupModelSet({make: this.elements.make.val()})
this.collection.fetch();
console.log(this.collection);
},
onModelChange: function(event) {
var VehicleLookupTrimInstance = new VehicleLookupTrimSet({make: this.elements.make.val(), model: this.elements.model.val()})
VehicleLookupTrimInstance.fetch();
},
onTrimChange: function(event) {
},
renderItem: function(object, item) {
console.log(item);
}
});
// Our module now returns our view
return new BrowseVehicleView;
});
The above is console.log(this.collection) is returning an object with many property which am not sure how to use. But, I noticed that there is a method "models" and inside models there is many number of objects, each represent the value of the json.
Any ideas how i can loop through the object?
this.collection.fetch({
success: function(collection, response) {
_.each(collection.models, function(model) {
console.log(model.toJSON());
})
}
});

Resources