Why i get error
require.js:5 Uncaught Error: Module name "views/concerts/ConcertView"
has not been loaded yet for context: _
define(function (require) {
var $ = require('jquery'),
Marionette = require('marionette'),
WrapperView = require('views/WrapperView'),
ConcertInfoAddView = require('views/concertInfo/ConcertInfoAddView'),
ConcertInfoModalView = require('views/concertInfo/ConcertInfoModalView'),
ConcertInfoWrapperView = require('views/concertInfo/table/ConcertInfoWrapperView'),
ConcertInfoCollection = require('collections/ConcertInfoCollection'),
Template = require('text!templates/concerts/concert-main.html');
var moment = require('moment');
var ConcertView = Marionette.View.extend({
initialize : function() {
this.listenTo(this.model, 'sync');
},
modelEvents : {
sync : function() {
WrapperView.showChildView('Content', this);
this.ConcertInfoModalView = new ConcertInfoModalView();
this.showChildView('createBody', new ConcertInfoAddView({concertId : this.model.get('id')}));
this.showChildView('tableConcerts', new ConcertInfoWrapperView());
this.showChildView('modalArea', this.ConcertInfoModalView);
ConcertInfoCollection.getConcertInfo(this.model.get('id'));
}
},
regions : {
'createBody' : '.create-body',
'tableConcerts' : '.table-concerts',
'modalArea' : '.modal-area'
},
template : function (ops) {
var date = ops.date;
var dateString = moment.unix(date).format("DD.MM.YYYY HH:mm:ss");
ops.date = dateString;
return _.template(Template)(ops);
},
getInfoModalView : function () {
return this.ConcertInfoModalView;
},
onRender : function () {
}
});
return ConcertView;});
Its ConcertView
define(function(require) {
var _ = require('underscore');
var Backbone = require('backbone'),
Marionette = require('marionette'),
ConcertInfoModalView = require('views/concertInfo/ConcertInfoModalView'),
ConcertInfoCollection = require('collections/ConcertInfoCollection'),
ConcertView = require('views/concerts/ConcertView'),
Template = require('text!templates/concertInfo/table/concertInfo-item.html');
var bootbox = require('bootbox');
var ConcertInfoItemView = Marionette.View.extend({
tagName : 'tr',
ui : {
edit : '#editButton',
delete : '#deleteButton'
},
events : {
'click #ui.edit' : 'edit',
'click #ui.delete' : 'delete'
},
edit : function () {
var concertModalView = ConcertView.getInfoModalView();
concertModalView.setModel(this.model);
$('#concertInfo-edit').modal('show');
},
delete : function () {
var self = this;
bootbox.confirm({
size: 'small',
message: "Are you sure?",
callback: function(result){
if(result){
self.model.destroy(null, {
success : function(model, response) {
noty({
text : response.notice,
type : response.type
});
},
error : function (model, response) {
if(_.isArray(response.responseJSON.notice)){
_.each(response.responseJSON.notice, function (res) {
noty({
text : res,
type : response.responseJSON.type
});
});
}else{
noty({
text : response.responseJSON.notice,
type : response.responseJSON.type
});
}
}
});
}
}
});
},
template : function(ops) {
return _.template(Template)(ops);
}
});
return ConcertInfoItemView;});
Its where i require it, why error?
I try not require it here, and require in other file, work fine
Related
UPDATE: I've updated my views to show how I resolved this question using information from the accepted answer.
I'd like to update/increment an attribute ('video_views') of my Backbone JS model via a click event from my view. But, as a Backbone rookie, I'm not sure how to accomplish this exactly.
I'd like the 'video_views' attribute to increment by one with the playVideo event (click).
Thanks for the help!
Here is the structure of my JSON from my API:
{
"id": 8,
"name": "Bike to work day",
"slug": "bike-work-day",
"tagline": "A brief tagline about the video.",
"description": "This is a test.",
"created": "2015-02-06T15:22:26.342658Z",
"website": "http://thevariable.com/",
"logo": "http://dev.thevariable.com/media/brands/logos/test_logo.jpeg",
"video": "http://dev.thevariable.com/media/brands/videos/3D463BC3-38B8-4A6F-BE93-3F53E918EC3B-3533-00000118880074BA_1.1.mp4",
"video_thumbnail": "http://dev.thevariable.com/media/brands/video_thumbnails/3D463BC3-38B8-4A6F-BE93-3F53E918EC3B-3533-00000118880074BA_1.1.mp4.jpg",
"links": {
"self": "http://dev.thevariable.com/api/brands/bike-work-day"
},
"status_display": "published",
"video_views": 0
}
Here are my Backbone views:
var TemplateView = Backbone.View.extend({
templateName: '',
initialize: function () {
this.template = _.template($(this.templateName).html());
},
render: function () {
var context = this.getContext(), html = this.template(context);
this.$el.html(html);
},
getContext: function () {
return {};
}
});
var HomePageView = TemplateView.extend({
templateName: '#home-template',
events: {
'click video': 'updateCounter',
'click .video video': 'playVideo',
'click .sound': 'muteVideo',
'click .js-open-card': 'openCard'
},
initialize: function (options) {
var self = this;
TemplateView.prototype.initialize.apply(this, arguments);
app.collections.ready.done(function () {
app.brands.fetch({success: $.proxy(self.render, self)});
});
},
getContext: function () {
return {brands: app.brands || null};
},
updateCounter: function (e) {
var id = $(e.currentTarget).data('id');
var item = self.app.brands.get(id);
var views = item.get('video_views');
var video = this.$('.video video');
// Only update the counter if the video is in play state
if (video.prop('paused')) {
item.save({video_views: views + 1}, {patch: true});
this.render();
}
},
playVideo: function () {
var video = this.$('.video video');
if (video.prop('paused')) {
video[0].play();
} else {
video.get(0).pause();
}
},
muteVideo: function (e) {
e.preventDefault();
var video = this.$el.parent().find('video');
video.prop('muted', !video.prop('muted'));
this.$('.sound').toggleClass('is-muted');
},
openCard: function (e) {
e.preventDefault();
this.$el.toggleClass('is-open');
this.$el.closest('.card-container').toggleClass('is-open');
}
});
And my Backbone models:
var BaseModel = Backbone.Model.extend({
url: function () {
var links = this.get('links'),
url = links && links.self;
if (!url) {
url = Backbone.Model.prototype.url.call(this);
}
return url;
}
});
app.models.Brand = BaseModel.extend({
idAttributemodel: 'slug'
});
var BaseCollection = Backbone.Collection.extend({
parse: function (response) {
this._next = response.next;
this._previous = response.previous;
this._count = response.count;
return response.results || [];
},
getOrFetch: function (id) {
var result = new $.Deferred(),
model = this.get(id);
if (!model) {
model = this.push({id: id});
model.fetch({
success: function (model, response, options) {
result.resolve(model);
},
error: function (model, response, options) {
result.reject(model, response);
}
});
} else {
result.resolve(model);
}
return result;
}
});
app.collections.ready = $.getJSON(app.apiRoot);
app.collections.ready.done(function (data) {
app.collections.Brands = BaseCollection.extend({
model: app.models.Brand,
url: data.brands
});
app.brands = new app.collections.Brands();
});
Just increment that attribute on the model and save it.
var views = model.get('video_views');
model.set({video_views: views + 1});
model.save();
I am a novice to backbone and need your help. I am facing an issue where I am not able to load an external template.
Here's the question:
I have a home_template.html which has a div i need to populate with an external template
<div class="ASContainer" id="asContainerView">
</div>
Now I have a Homeview.js
define([
'jquery',
'underscore',
'backbone',
'marionette',
'text!templates/home/homeTemplate.html',
'text!templates/home/activityTemplate.html',
'text!templates/compose/composeTemplate.html',
'text!templates/comments/commentsTemplate.html',
'views/home/ActivityListView',
'views/ComposePost/ComposePostView',
'views/ComposePost/WSListView',
], function ($, _, Backbone, Marionette, homeTemplate, activityTemplate, composeTemplate, commentsTemplate, ActivityListView, ComposePostView, WSListView) {
var HomeView = Backbone.View.extend({
el : $("#page"),
transition : 'slide',
activitiesListView : null,
initialize : function () {
this.$el.attr('data-transition', this.transition);
this.currentUserLogin = currentUserLogin;
var that = this;
this.activityId = this.options.activityId;
this.workspaceUrl = this.options.workspaceUrl;
this.context = this.options.parentContext;
},
events : {
'click #composePost' : 'onComposePost',
'click #btnPost' : 'onPostClick',
'click #cancelpost' : 'onCancelClick',
'click #comments' : 'OnCommentsClick',
'click #LeftNavIcon' : 'OnLeftNavigationClick',
},
render : function () { debugger
var that = this;
$('.menu li').removeClass('active');
$('.menu li a[href="#"]').parent().addClass('active');
that.callAjaxReload("homeTemplate.html", "aaa", "AS_Content");
this.$el.html(homeTemplate);
$("#userloggedin").text(currentUserLogin);
//var sidebarView = new SidebarView();
//sidebarView.render();
},
cleanup: function() {
this.undelegateEvents();
$(this.el).empty();
},
getActivitiesForWorkspace: function(ActStreamPageSize, activityId) { debugger;
try {
//LogInfoStart('getActivitiesStreamAjaxCommand');
var BrowserTimeZone = getTimezoneName();
$.ajax({
type : "POST",
url : siteBaseUrl + '/ActivityStreamClientService.svc/GetActivityStreamForWorkSpace',
contentType : "application/json; charset=utf-8",
dataType : 'json',
cache : false,
data : JSON.stringify({
workspaceUrl : siteBaseUrl,
userLoginName : currentUser,
filterValue : "All",
searchTxt : '',
searchFilter : "All", //add
searchTag : '', //add
activityId : activityId,
pageSize : 5,
commentCount : 9999,
tabContext : "MY",
customFilter : '',
activityMode : '',
time : new Date(), // need to add this for iPhone caching ajax posts problem!
browserTimeZone : BrowserTimeZone, // added for time zone changes in new ux
MySiteMode : '',
MySiteLogggedInUserName : '',
MySiteProfileVisitorruserName : '',
MySiteDetails : ''
}),
processData : true,
success : function (msg) { debugger;
//Define collection
var model = Backbone.Model.extend({});
var collection = Backbone.Collection.extend({
model : model
});
//var activityListView = ActivityListView({model : activitiesList});
//Add it to the collection after fetch
msgActivities = msg.GetActivityStreamForWorkSpaceResult;
var activitiesList = new collection(msgActivities);
//gtemplate = $('#personTemplate').html();
//var template: _.template( $('#personTemplate').html());
if (activityId <= 0) {
console.log("here");
$("#asContainerView").html(ActivityListView({model : activitiesList}).el);
}
else {
console.log("I am there");
$(new ActivityListView({model : activitiesList}).el).appendTo("#asContainerView");
}
lastactivityId = msgActivities[(msgActivities.length - 1)].ActivityID;
//Add collection to context
// that.context.collections.add(activitiesCollection, collectionTitle);
//that.context.currentCollectionNameId = collectionTitle; // for details page to work (ws url of stream is different than the activity ws url!!
//that.GetActivitiesSuccess(msg, dfd, that.eventData.onSuccessCallback);
//customFilterValue = "all";
},
error : function (err) {
//LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.execute - Error', '', //that.context.parentContext.mainGlobalObject.CurrentUser, err);
//$.utilsSystem.alert('Error getting activities.', 'single');
//if (onSuccessCallback) onSuccessCallback();
}
});
} catch (err) {
// LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.GetActivitiesError', '', $.SX.mainGlobalObject.CurrentUser, err);
}
},
callAjaxReload: function (url, parameter, classname) { debugger;
var that = this;
console.log(classname);
// $.ajax({
//url:url,
//dataType:datatype,
//success:function(data){
// }
//GetConfigurationSettings
var BrowserTimeZone = getTimezoneName();
$.ajax({
type : "GET",
url : siteBaseUrl + '/ActivityStreamClientService.svc/GetConfigurationSettings', //this.ActivitiesStreamOptions.ACTSTREAMGETCONFIGITEMURL,
contentType : "application/json; charset=utf-8",
dataType : 'json',
data : {
configurationItem : "ActivityStreamCount",
workspaceUrl : siteBaseUrl //this.ActivitiesStreamOptions.ActStreamWorkspaceUrl
},
async : false,
success : function (msg) { debugger;
//ActivitiesStreamOptions.ActStreamPageSize = msg.GetConfigurationSettingsResult[0];
ActivityStreamPageSize = msg.GetConfigurationSettingsResult[0];
that.**getActivitiesForWorkspace**(msg.GetConfigurationSettingsResult[0], 0);
debugger;
//console.log(ActivitiesStreamOptions.ActStreamPageSize);
// ActivitiesStreamOptions.ActStreamFilterValue = '';
},
error : function (err) {
console.log("Error: Hasan");
//LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.execute - Error', '', that.context.parentContext.mainGlobalObject.CurrentUser, err);
// that.ActivitiesStreamOptions.ActStreamPageSize = 5;
}
});
//})
//$('.'+classname).html(data);
},
});
return HomeView;
});
Now this HomeView js has two functions. callAjaxReload and getActivitiesForWorkspace.
The render calls callAjaxReload which has an ajax function which on success calls getActivitiesForWorkspace.Now getActivitiesForWorkspace also has an ajax function and on whose success I have to pass the model to another View ActivityList View and appends that the template under the div id asContainerView.
The problem which I am facing is that the this line below fails to load the ActivityListView.
$("#asContainerView").html(ActivityListView({model : activitiesList}).el);
I get an error that ActivityListView is undefined.
Can anybody help me here.
The ActivityListView.js is
define([
'jquery',
'underscore',
'backbone',
'marionette',
'views/home/ActivityListItemView',
'text!templates/home/activityTemplate.html',
], function ($, _, Backbone, Marionette, ActivityListItemView, activityTemplate) {
var ActivityListView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
var activities = this.model.models;
var len = activities.length;
//var startPos = (this.options.page - 1) * 8;
//var endPos = Math.min(startPos + 8, len);
var startPos = 0;
var endPos = len;
//$(this.el).html('<ul class="thumbnails"></ul>');
for (var i = startPos; i < endPos; i++) {
{ //$(this.el).append(new ActivityListItemView({model: activities[i]}).initialize);
//console.log("activities[i]:"activityListItemView.model.attributes.ActivityTypeSourceName);
var activityListItemView = new ActivityListItemView({ model: activities[i] });
$(this.el).append(activityListItemView.el);
}
//console.log(activityListItemView.el);
//var personView = new PersonView({ model: person });
}
//$(this.el).append(new Paginator({model: this.model, page: this.options.page}).render().el);
return this;
}
});
});
and this calls ActivityListItemView.js
define([
'jquery',
'underscore',
'backbone',
'marionette',
'text!templates/home/activityTemplate.html',
], function ($, _, Backbone, Marionette, activityTemplate) {
var ActivityListItemView = Backbone.View.extend({
tagName: "div",
template: activityTemplate,
//my_template: _.template(gtemplate1),
//my_template: _.template("<p class=\"AS_Content\"> <%= ActivityContent %> </p> "),
initialize: function(){
this.render();
},
render: function(){ debugger;
//$(this.el).html(this.template(this.model.toJSON()));
this.$el.html(_.template(this.template, { user: this.model.attributes }));
//this.$el( this.template(this.model.toJSON()));
//this.$el.html( this.template(this.model.toJSON()));
}
});
});
Thanks
You have:
$("#asContainerView").html(ActivityListView({model : activitiesList}).el);
but your syntax is off; when you want to instantiate a new Backbone.View you need to use the new keyword:
$("#asContainerView").html(new ActivityListView({model : activitiesList}).el);
Your requirejs definitions should return ActivityListView and ActivityListItemView
The function should return an object that defines the module
see http://www.requirejs.org/docs/api.html#defdep
My controller code is here.
spine.module("communityApp", function (communityApp, App, Backbone, Marionette, $, _) {
"use strict";
communityApp.Controllers.pforumController = Marionette.Controller.extend(
{
init: function(){
var func = _.bind(this._getpforum, this);
var request = App.request('alerts1:entities' , {origin:'pforum'});
$.when(request).then(func)
},
_getpforum:function(data){
var pforumCollectionView = new communityApp.CollectionViews.pforumCollectionViews({
collection: data
});
communityApp.activeTabView = pforumCollectionView;
// Populating the data
communityApp.activeTabLayout.pforum.show(pforumCollectionView);
},
});
});
view code is here
spine.module("communityApp", function (communityApp, App, Backbone, Marionette, $, _) {
// Load template
var a;
var pforumTemplateHtml = App.renderTemplate("pforumTemplate", {}, "communityModule/tabContainer/pforum");
// Define view(s)
communityApp.Views.pforumView = Marionette.ItemView.extend({
template: Handlebars.compile($(pforumTemplateHtml).html()),
tagName: "li",
onRender: function () {
this.object = this.model.toJSON();
},
events: {
"click #postcomment" : "alrt",
"click #recent-btn": "recent",
"click #my-posts": "myposts",
"click #popular-btn": "popular",
"click #follow-btn": "follow",
"click #my-posts": "LeftLinks",
"click #popular-btn": "LeftLinks",
"click #follow-btn": "LeftLinks"
},
postcomments : function ()
{
$("#recent-post-main-container").hide();
$("#recent-post-main-container2").show();
},
alrt : function ()
{
alert ("In Progress ......");
},
showCommentEiditor : function (){
$(".comment-popup-container").show();
$(".comment-txt-area").val('');
},
showPforumTab : function ()
{
$("#recent-post-main-container2").show();
$("#recent-post-main-container").hide();
},
showComments : function(){
$("#loading").show();
$(".tab-pane").hide();
$(".left-content").hide();
$("#recent-post-main-container2").show();
//$(".left-content-commentEditor").show();
$(".comm-tab-content-container").css('height','200px');
$(".comment-txt-area").val('');
$(".left-content-comment").show();
},
hideCommentPopup : function ()
{
$("#public-question-comment").hide();
},
// Show Loading sign
showLoading : function () {
$('#loading').show();
},
// UnLoading Function
hideLoading : function (){
$('#loading').hide();
},
// Add New Event Function
addEvent : function()
{
//$("#name").val(getBackResponse.user.FullName);
//$("#phone").val(getBackResponse.user.CellPhone);
//$("#email").val(getBackResponse.user.UserName);
$(".overly.addevent").show();
$('#lang').val(lat);
$('#long').val(long);
document.getElementById("my-gllpMap").style.width = "100%";
var my_gllpMap = document.getElementById("my-gllpMap");
google.maps.event.trigger( my_gllpMap, "resize" );
},
setValues : function(key,value)
{
window.localStorage.setItem(key,value);
},
getValues : function (key)
{
return window.localStorage.getItem(key);
},
closeAddEvent:function ()
{
$(".overly.addevent").hide();
},
// Show Over lay
showOverly:function ()
{
$('.overly-right-tab').show();
},
// Hide Loading sign
hideOverly : function()
{
$('.overly-right-tab').hide();
},
LeftLinks: function (e) {
var elem = $(e.target).closest('a');
var elem = $(e.target).closest('a');
var event = elem.attr('name');
switch (event) {
case "myposts":
var _this = $.extend({}, this, true);
_this.event = 'myposts';
this.LinkUrl.call(_this);
//$("#my-posts").addClass('active');
//$("#public-fourm-top-tab").addClass('TabbedPanelsTabSelected');
//$(".types").removeClass('active');
break;
case "recents":
var _this = $.extend({}, this, true);
_this.event = 'recents';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#recent-btn").addClass('active')
//$("#pforum").removeClass('active');
// $("#recent").addClass('active');
break;
case "populars":
var _this = $.extend({}, this, true);
_this.event = 'populars';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#popular-btn").addClass('active')
// $("#pforum").removeClass('active');
//$("#popular").addClass('active');
break;
case "follows":
var _this = $.extend({}, this, true);
_this.event = 'follows';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#follow-btn").addClass('active')
break;
}
},
LinkUrl: function (modalThis) {
communityApp.activeTabView.collection = []; // currently empty data
communityApp.activeTabView.render();
className: 'comm-main-container'
// uncomment these lines when getting data fro web service route, it will repopulate the data
var func = _.bind(function (data) {
communityApp.activeTabView.collection = data;
communityApp.activeTabView.render();
}, this);
switch (this.event) {
case "myposts":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
case "recents":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
case "populars":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
origin1:'popular',
event: this.event
})).then(func);
break;
case "follows":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
}
return true;
}
});
// define collection views to hold many communityAppView:
communityApp.CollectionViews.pforumCollectionViews = Marionette.CollectionView.extend({
tagName: "ul",
itemView: communityApp.Views.pforumView
});
});
Whenever I need to share an event between a view and controller I usually wire up the listeners within the module that instantiates the controller. This example is a bit contrived, but it gets the point across. The full working code is in this codepen. The relevant bit is copied here. Notice the line this.listenTo(view, 'itemview:selected', this.itemSelected); where the view's event triggers a method on the controller.
App.module("SampleModule", function(Mod, App, Backbone, Marionette, $, _) {
// Define a controller to run this module
// --------------------------------------
var Controller = Marionette.Controller.extend({
initialize: function(options){
this.region = options.region
},
itemSelected: function (view) {
var logView = new LogView();
$('#log').append(logView.render('selected:' + view.cid).el);
},
show: function(){
var collection = new Backbone.Collection(window.testData);
var view = new CollectionView({
collection: collection
});
this.listenTo(view, 'itemview:selected', this.itemSelected);
this.region.show(view);
}
});
// Initialize this module when the app starts
// ------------------------------------------
Mod.addInitializer(function(){
Mod.controller = new Controller({
region: App.mainRegion
});
Mod.controller.show();
});
});
The other way to accomplish this, if you cannot wire it all up within the same module, is to use Marionette's messaging infrastructure. For example, you can use the application's event aggregator to pass events around.
I am creating a BackboneJS project. It works fine in Chrome and Safari, but in Firefox I get errors that stop my app from loading and I cannot work out why.
The error is in my jQuery file but it is obviously something in my app that is triggering it because the jQuery library is fine on its own.
It is throwing an error on the second line of the jQuery "createSafeFragment" method:
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
My main.js that runs the app:
Backbone.View.prototype.close = function () {
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'login' : 'login',
'register' : 'register',
'rosters' : 'rosters',
'workplaces' : 'workplaces',
'groups' : 'groups',
'shifts' : 'shifts',
'logout' : 'logout'
},
content : '#content',
initialize: function () {
window.headerView = new HeaderView();
$('.header').html(window.headerView.render().el);
},
home: function () {
window.homePage = window.homePage ? window.homePage : new HomePageView();
app.showView( content, window.homePage);
window.headerView.select('home');
},
register: function () {
window.registerPage = window.registerPage ? window.registerPage : new RegisterPageView();
app.showView( content, window.registerPage);
window.headerView.select('register');
},
login: function() {
app.showView( content, new LoginPageView());
window.headerView.select('login');
},
rosters: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new RosterPageView());
window.headerView.select('rosters');
}
},
groups: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new GroupsPageView());
window.headerView.select('groups');
}
},
shifts: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new ShiftsPageView());
window.headerView.select('shifts');
}
},
workplaces: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new WorkplacesPageView());
window.headerView.select('workplaces');
}
},
logout: function () {
window.headerView.toggleLogin(false);
this.login();
},
showView: function(selector, view) {
if (this.currentView)
this.currentView.close();
$(selector).html(view.render().el);
this.currentView = view;
return view;
}
});
Utils.loadTemplates(['HomePageView', 'HeaderView', 'LoginPageView', 'RegisterPageView',
'RostersPageView', 'GroupsPageView', 'ShiftsPageView', 'UserListView',
'GroupListView', 'ShiftListView', 'SearchedUserListView', 'SearchedGroupListView',
'GroupRosterView', 'RosterListView', 'WorkplacesPageView', 'WorkplaceListView',
'SearchedWorkplaceListView', 'RosterJoinListView', 'GroupUserListView',
'WorkplaceRosterView', 'WorkplaceUserListView', 'RosterShiftView'], function(){
app = new AppRouter();
Backbone.history.start();
});
And my Util.js:
Utils = {
//template stuff
templates: {},
loadTemplates: function(names, callback) {
var that = this;
var loadTemplate = function(index) {
var name = names[index];
$.get('tpl/' + name + '.html', function(data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
};
loadTemplate(0);
},
get: function(name) {
return this.templates[name];
},
//error stuff
showAlertMessage: function(message, type){
$('#error').html(message);
$('.alert').addClass(type);
$('.alert').show();
},
showErrors: function(errors) {
_.each(errors, function (error) {
var controlGroup = $('.' + error.name);
controlGroup.addClass('error');
controlGroup.find('.help-inline').text(error.message);
}, this);
},
hideErrors: function () {
$('.control-group').removeClass('error');
$('.help-inline').text('');
},
//validator stuff
validateModel: function(model, attrs){
Utils.hideErrors();
var valError = model.validate(attrs);
if(valError){
Utils.showErrors(valError);
return false;
}
return true;
},
//loading stuff
toggleLoading: function(toggle){
$('#loading').css('visibility', toggle ? 'visible' : 'hidden');
},
//login stuff
login: function(auth){
window.headerView.toggleLogin(true);
Backbone.history.navigate("", true);
},
checkLoggedIn: function(){
if(!window.userId){
window.headerView.toggleLogin(false);
Backbone.history.navigate("login", true);
return false;
}
return true;
},
//util methods
formatDate: function(date){
var formattedDate = '';
formattedDate += date.getFullYear() + '-';
formattedDate += date.getMonth()+1 + '-';
formattedDate += date.getDate();
return formattedDate;
},
formatDateForDisplay: function(date){
var formattedDate = '';
formattedDate += date.getDate() + '/';
formattedDate += date.getMonth()+1 + '/';
formattedDate += date.getFullYear() + ' - ';
formattedDate += ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
return formattedDate;
},
formatDateForGroup: function(date){
var formattedDate = '';
formattedDate += date.getDate() + '/';
formattedDate += date.getMonth()+1;
return formattedDate;
},
showPopup: function(id, buttons, title, content){
var popup = $(id);
popup.dialog({
modal: true,
title: title,
buttons: buttons
});
popup.find('#popupContent').html(content);
}
};
Someone please help me as this is driving me crazy! Firefox only...
I was also experiencing this problem. You can reproduce this error by doing:
$(window).append('bla');
Mine was cause by a combination of this:
click
and
function doIt(){
var newElm = $('<span>hi</span>');
$(this).append(newElm);
//now this === window, and not what I was expecting the a-element
}
This all happened because I expected the click would have been binded in a proper more-jquery-ish way to the a element. But someone decided to use 1999 code ;p. I expected for the method to be bound like this:
$("a").click(doIt);
In which case this would have been bound to the a-element and not to the window.
benhowdle89 figured out that I was appending to content when I should have been appending to this.content.
It is also a good idea to always use JSFiddle I have realised, so other people can see your problem on their own.
Thanks to benhowdle89!
I've been all over the related questions but couldn't find an answer to my problem.
http://s1308.hizliresim.com/1d/5/r50lw.png
When I click "Kredi Yükle" a popup should appear but nothing happens and i get these console errors.
What should i do?
In related js file :
CreditLoadingAmrEditor = Class.create({
SELECTION_WINDOW : "wndCreditLoadingHelper",
BUTTON_OK : "btnLoadCreditOk",
BUTTON_CANCEL : "btnLoadCreditCancel",
CREDIT_AMOUNT : "fld_credit_amount",
initialize: function(owner) {
this.owner = owner;
this.browser = owner.browser;
this.buttonOk = $(this.BUTTON_OK);
this.buttonCancel = $(this.BUTTON_CANCEL);
this.selectionWindow = this.initializeHelper(this.SELECTION_WINDOW);
var containers = $$("div[id='loadingCreditContainer']");
if (containers && containers.size() > 0) {
this.container = containers[0];
this.editorManager = new EditorManager("loadingCreditContainer");
this.creditAmount = $(this.CREDIT_AMOUNT).instance;
}
this.browser.addToolClickListener(this);
this.buttonOk.observe(iconstants.KEY_CLICK, this.okClick.bindAsEventListener(this));
this.buttonCancel.observe(iconstants.KEY_CLICK, this.closeClick.bindAsEventListener(this));
},
initializeHelper: function(windowName) {
var result = $(windowName);
if (result){
result.remove();
document.body.appendChild(result);
}
return result;
},
toolClick: function(browser, toolType) {
if (toolType == browser.TOOL_LOAD_CREDIT) {
this.show();
}
return false;
},
show: function(callback) {
this.callback = callback;
FSystem.registerWindow(this.selectionWindow, true, true);
},
hide: function() {
FSystem.unregisterWindow(this.selectionWindow);
},
okClick: function() {
if (this.creditAmount.getValue() >= 0) {
this.hide();
this.requestForLoadingCredit();
} else {
window.alert(localize("value_must_greater_than_0"));
}
},
closeClick: function() {
this.hide();
},
requestForLoadingCredit: function() {
FSystem.startWait();
new Ajax.Request(
iconstants.URL_CREDIT_LOADING_AMR,
{
method : iconstants.METHOD_POST,
parameters : {mid:this.browser.getSelectedId(),ca:this.creditAmount.getValue()},
onComplete : this.responseForDeviceReading.bind(this),
onException : null
});
},
responseForDeviceReading: function(transport) {
FSystem.stopWait();
var JSON = transport.responseText.evalJSON();
if (JSON.status == iconstants.AJAX_STATUS_OK){
//if (confirm(JSON.message)) {
window.open(JSON.url, '_newtab', 'width=1280,height=800');
//}
} else {
alert(JSON.message);
}
}
});
Such type of error occur when your object is not initialized. You are trying to access a method of such object which is not initialized. Please check your object initialization.