'jsonp' is undefined(AngluarJS with PubNub) - javascript

I'm learning Angular and creating a chat app using the PubNub lib then I get this error when I navigate to the page where I can create room or join a chat.
TypeError: Cannot read property 'jsonp' of undefined
at window.PUBNUB.CREATE_PUBNUB (https://cdn.pubnub.com/pubnub-3.7.20.js:2719:14)
at new SELF (https://cdn.pubnub.com/pubnub-3.7.20.js:2739:16)
at a.exports.e.value (http://localhost:9000/bower_components/pubnub-angular/dist/pubnub-angular-3.1.0.min.js:16:64)
at Object.b.init (http://localhost:9000/bower_components/pubnub-angular/dist/pubnub-angular-3.1.0.min.js:4:87)
at new <anonymous> (http://localhost:9000/scripts/controllers/main.js:13:15)
at invoke (http://localhost:9000/bower_components/angular/angular.js:4535:17)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4543:27)
at http://localhost:9000/bower_components/angular/angular.js:9395:28
at link (http://localhost:9000/bower_components/angular-route/angular-route.js:977:26)
at invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:9039:9) <div ng-view="" class="ng-scope" data-ng-animate="1">(anonymous function) # angular.js:12722(anonymous function) # angular.js:9490invokeLinkFn # angular.js:9041nodeLinkFn # angular.js:8533compositeLinkFn # angular.js:7929publicLinkFn # angular.js:7809boundTranscludeFn # angular.js:7947controllersBoundTransclude # angular.js:8560update # angular-route.js:935Scope.$broadcast # angular.js:16573(anonymous function) # angular-route.js:619processQueue # angular.js:14991(anonymous function) # angular.js:15007Scope.$eval # angular.js:16251Scope.$digest # angular.js:16069Scope.$apply # angular.js:16359done # angular.js:10791completeRequest # angular.js:10989requestLoaded # angular.js:10930
and don't what it means, help needed?
My Code is here
angular.module('pnChatApp')
.controller('MainCtrl', ['$scope', '$rootScope', '$location', 'Pubnub', function ($scope, $rootScope, $location, Pubnub) {
var _ref;
if (!Pubnub.init()) {
$location.path('/join');
}
$scope.controlChannel = '__controlChannel';
$scope.channels = [];
//Publish Chat
$scope.publish = function() {
if (!$scope.selectedChannel) {
return;
}
Pubnub.ngPublish({
channel: $scope.selectedChannel,
message: {
text: $scope.newMessage,
user: $scope.data.username
}
});
return $scope.newMessage = '';
};
//Create Channel
$scope.createChannel = function() {
var channel;
console.log('Creating Channel...');
channel = $scope.newChannel;
$scope.newChannel = '';
Pubnub.ngGrant( {
channel: channel,
read: true,
write: true,
callback: function(){
return console.log(channel + 'All Set', arguments);
}
});
Pubnub.ngGrant( {
channel: channel + '-pnpres',
read: true,
write: false,
callback: function(){
return console.log(channel + 'Presence All Set', arguments);
}
});
Pubnub.ngPublish({
channel: $scope.controlChannel,
message: channel
});
return setTimeout(function() {
$scope.subscribe(channel);
return $scope.showCreate = false;
}, 100);
};
$scope.subscribe = function(channel) {
var _ref;
console.log('Subscribing...');
if (channel === $scope.selectedChannel) {
return;
}
if ($scope.selectedChannel) {
Pubnub.ngUnsubscribe({
channel: $scope.selectedChannel
});
}
$scope.selectedChannel = channel;
$scope.messages = ['Welcome to ' + channel];
Pubnub.ngSubscribe({
channel: $scope.selectedChannel,
state: {
"city": ((_ref = $rootScope.data) !== null ? _ref.city : void 0) || 'unknown'
},
error: function() {
return console.log(arguments);
}
});
$rootScope.$on(Pubnub.ngPrsEv($scope.selectedChannel), function(ngEvent, payload) {
return $scope.$apply(function() {
var newData, userData;
userData = Pubnub.ngPresenceData($scope.selectedChannel);
newData = {};
$scope.users = Pubnub.map(Pubnub.ngListPresence($scope.selectedChannel), function(x) {
var newX;
newX = x;
if (x.replace) {
newX = x.replace(/\w+__/, "");
}
if (x.uuid) {
newX = x.uuid.replace(/\w+__/, "");
}
newData[newX] = userData[x] || {};
return newX;
});
return $scope.userData = newData;
});
});
Pubnub.ngHereNow({
channel: $scope.selectedChannel
});
$rootScope.$on(Pubnub.ngMsgEv($scope.selectedChannel), function(ngEvent, payload) {
var msg;
msg = payload.message.user ? "[" + payload.message.user + "]" + payload.message.text : payload.message.text;
return $scope.$apply(function() {
return $scope.messages.unshift(msg);
});
});
return Pubnub.ngHistory({
channel: $scope.selectedChannel,
auth_key: $scope.authKey,
count: 500
});
};
Pubnub.ngSubscribe({
channel: $scope.controlChannel
});
$rootScope.$on(Pubnub.ngMsgEv($scope.controlChannel), function(ngEvent, payload) {
return $scope.$apply(function() {
if ($scope.channels.indexOf(payload.message) < 0) {
return $scope.channels.push(payload.message);
}
});
});
return Pubnub.ngHistory({
channel: $scope.controlChannel,
count: 500
});
$scope.channels = 'TheWaitingRoom';
return $scope.createChannel();
}]);

The reason for jsonp error is that Pubnub.init has required options argument
Pubnub.init({ publish_key: 'your pub key', subscribe_key: 'your sub key' });
https://github.com/pubnub/pubnub-angular

Related

Uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator

I am facing the following issue:
ActionController::RoutingError (uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator):
app/controllers/spree/api/aramex_address_controller.rb:2:in <class:AramexAddressController>
app/controllers/spree/api/aramex_address_controller.rb:1:in <top (required)>
I included the following in my controllers/spree/api/aramex_address_controller.rb:
class Spree::Api::AramexAddressController < ApplicationController
include AramexAddressValidator
# fetch cities from aramex api
def fetch_cities_from_aramex_address
response = []
zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
if zones.map(&:countries).flatten.map(&:iso).include?(params['country_code'])
response = JSON.parse(fetch_cities(params['country_code']))['Cities']
end
respond_to do |format|
format.json { render :json => response, :status => 200 }
end
end
# Validate address for aramex shipping
def validate_address_with_aramex
begin
zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
final_response = {}
if zones.map(&:countries).flatten.map(&:iso).include?(params[:b_country])
final_response[:b_errors] = confirm_address_validity(params[:b_city], params[:b_zipcode], params[:b_country])
end
if zones.map(&:countries).flatten.map(&:iso).include?(params[:s_country]) && params[:use_bill_address] == "false"
final_response[:s_errors] = confirm_address_validity(params[:s_city], params[:s_zipcode], params[:s_country])
end
rescue
return true
end
respond_to do |format|
format.json { render :json => final_response, :status => 200 }
end
end
# Confirm address validity with Aramex address validatio API
def confirm_address_validity(city, zipcode, country)
response = JSON.parse(validate_address(city, zipcode, country))
if response['HasErrors'] == true
if response['SuggestedAddresses'].present?
response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + response['SuggestedAddresses'].map{|data| data['City']}.join(', ')
else
if response['Notifications'].first['Code'] == 'ERR06'
response['Notifications'].map{|data| data['Message']}.join(', ')
else
cities_response = JSON.parse(fetch_cities(country, city[0..2]))
cities_response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + cities_response['Cities'].join(' ,')
end
end
end
end
end
In my route file I mentioned:
get 'validate_address_with_aramex', to: 'aramex_address#validate_address_with_aramex'
get 'fetch_cities_from_aramex_address', to: 'aramex_address#fetch_cities_from_aramex_address'
I included the following JS call for the submitted Aramex Ajax validation in assets/javascripts/spree/frontend/checkout/address.js:
Spree.ready(function($) {
Spree.onAddress = function() {
var call_aramex = true;
$("#checkout_form_address").on('submit', function(e) {
if ($('#checkout_form_address').valid()) {
var s_country = $("#order_ship_address_attributes_country_id").find('option:selected').attr('iso_code');
var s_zipcode = $("#order_ship_address_attributes_zipcode").val();
var s_city = $("#order_ship_address_attributes_city").val();
var b_country = $("#order_bill_address_attributes_country_id").find('option:selected').attr('iso_code');
var b_zipcode = $("#order_bill_address_attributes_zipcode").val();
var b_city = $("#order_bill_address_attributes_city").val();
if (call_aramex == true && (typeof aramex_countries !== 'undefined') && (aramex_countries.includes(b_country) || aramex_countries.includes(s_country))) {
e.preventDefault();
var error_id = $('#errorExplanation').is(':visible') ? '#errorExplanation' : '#manual_error'
$(error_id).html("").hide()
$.blockUI({
message: '<img src="/assets/ajax-loader.gif" />'
});
$.ajax({
url: "/api/validate_address_with_aramex",
type: 'GET',
dataType: "json",
data: {
s_country: s_country,
s_zipcode: s_zipcode,
s_city: s_city,
b_country: b_country,
b_zipcode: b_zipcode,
b_city: b_city,
use_bill_address: ($("#order_use_billing").is(":checked"))
},
success: function(result) {
$.unblockUI()
if (result.b_errors || result.s_errors) {
if (result.b_errors) {
$(error_id).append('<div>Billing Address ' + result.b_errors + ' </div>')
}
if (result.s_errors) {
$(error_id).append('<div>Shipping Address ' + result.s_errors + ' </div>')
}
if ((result.b_errors && !result.s_errors) && ($("#order_use_billing").is(":unchecked"))) {
$(".js-summary-edit").trigger("click")
}
$(error_id).show();
$('html, body').animate({
scrollTop: '0px'
}, 300);
} else {
call_aramex = false;
$('#checkout_form_address').submit()
}
},
error: function(xhr, status, error) {
$(error_id).append('Oops Something Went Wrong but you can process order')
$(error_id).show();
$.unblockUI()
$('html, body').animate({
scrollTop: '0px'
}, 300);
$('#checkout_form_address').submit()
}
});
}
}
})
var getCountryId, order_use_billing, update_shipping_form_state;
if (($('#checkout_form_address')).is('*')) {
($('#checkout_form_address')).validate({
rules: {
"order[bill_address_attributes][city]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 22)
}
},
"order[bill_address_attributes][firstname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 15)
}
},
"order[bill_address_attributes][lastname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 17)
}
},
"order[bill_address_attributes][address1]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
}
},
"order[bill_address_attributes][address2]": {
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
}
},
"order[bill_address_attributes][zipcode]": {
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 10)
}
},
"order[ship_address_attributes][city]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 22)
}
},
"order[ship_address_attributes][firstname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 15)
}
},
"order[ship_address_attributes][lastname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 17)
}
},
"order[ship_address_attributes][address1]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
}
},
"order[ship_address_attributes][address2]": {
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
}
},
"order[ship_address_attributes][zipcode]": {
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 10)
}
}
}
});
getCountryId = function(region) {
return $('#' + region + 'country select').val();
};
isCountryUsOrCa = function(country_id) {
return ["38", "232"].includes(country_id)
}
maxCharLimit = function(country_id, limit) {
if (["38", "232"].includes(country_id)) {
return limit;
} else {
return 255;
}
};
Spree.updateState = function(region) {
var countryId;
var cityId
countryId = getCountryId(region);
if (countryId != null) {
if (region == 'b') {
cityId = '#order_bill_address_attributes_city'
countryInputId = "#order_bill_address_attributes_country_id"
} else {
cityId = '#order_ship_address_attributes_city'
countryInputId = "#order_ship_address_attributes_country_id"
}
fill_cities($(countryInputId).find('option:selected').attr('iso_code'), cityId)
if (Spree.Checkout[countryId] == null) {
return $.get(Spree.routes.states_search, {
country_id: countryId
}, function(data) {
Spree.Checkout[countryId] = {
states: data.states,
states_required: data.states_required
};
return Spree.fillStates(Spree.Checkout[countryId], region);
});
} else {
return Spree.fillStates(Spree.Checkout[countryId], region);
}
}
};
fill_cities = function(country_code, cityId) {
$.ajax({
url: "/api/fetch_cities_from_aramex_address",
type: 'GET',
dataType: "json",
data: {
country_code: country_code
},
success: function(data) {
$(cityId).autocomplete({
source: data,
});
},
error: function() {}
});
}
Spree.fillStates = function(data, region) {
var selected, stateInput, statePara, stateSelect, stateSpanRequired, states, statesRequired, statesWithBlank;
statesRequired = data.states_required;
states = data.states;
statePara = $('#' + region + 'state');
stateSelect = statePara.find('select');
stateInput = statePara.find('input');
stateSpanRequired = statePara.find('[id$="state-required"]');
if (states.length > 0) {
selected = parseInt(stateSelect.val());
stateSelect.html('');
statesWithBlank = [{
name: '',
id: ''
}].concat(states);
$.each(statesWithBlank, function(idx, state) {
var opt;
opt = ($(document.createElement('option'))).attr('value', state.id).html(state.name);
if (selected === state.id) {
opt.prop('selected', true);
}
return stateSelect.append(opt);
});
stateSelect.prop('disabled', false).show();
stateInput.hide().prop('disabled', true);
statePara.show();
stateSpanRequired.show();
if (statesRequired) {
stateSelect.addClass('required');
}
stateSelect.removeClass('hidden');
return stateInput.removeClass('required');
} else {
stateSelect.hide().prop('disabled', true);
stateInput.show();
if (statesRequired) {
stateSpanRequired.show();
stateInput.addClass('required');
} else {
stateInput.val('');
stateSpanRequired.hide();
stateInput.removeClass('required');
}
statePara.toggle(!!statesRequired);
stateInput.prop('disabled', !statesRequired);
stateInput.removeClass('hidden');
return stateSelect.removeClass('required');
}
};
($('#bcountry select')).change(function() {
$('label.error').hide()
if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
$('#checkout_form_address').valid();
}
return Spree.updateState('b');
});
($('#scountry select')).change(function() {
$('label.error').hide()
if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
$('#checkout_form_address').valid();
}
return Spree.updateState('s');
});
Spree.updateState('b');
order_use_billing = $('input#order_use_billing');
order_use_billing.change(function() {
return update_shipping_form_state(order_use_billing);
});
update_shipping_form_state = function(order_use_billing) {
if (order_use_billing.is(':checked')) {
($('#shipping .inner')).hide();
return ($('#shipping .inner input, #shipping .inner select')).prop('disabled', true);
} else {
($('#shipping .inner')).show();
($('#shipping .inner input, #shipping .inner select')).prop('disabled', false);
return Spree.updateState('s');
}
};
return update_shipping_form_state(order_use_billing);
}
};
return Spree.onAddress();
});
Why am I am facing the issue mentioned at the top?
maybe you can try this:
namespace :spree do
namespace :api do
resources :aramex_address, only: [] do
get :validate_address_with_aramex
get :fetch_cities_from_aramex_address
end
end
end
words of advice I think it's better if you rename the fetch_cities_from_aramex_address with show method, so it still follow rails convenience
well here is the issue of constant lookup. Your constant that is AramexAddressValidator is missing because of the way you wrote class Spree::Api::AramexAddressController < ApplicationController
So if your module AramexAddressValidator is inside some scope use that scope also while including this module
For Ex. if its inside spree/aramex_address_validator use
include Spree::AramexAddressValidator

ionic cordova encrypt base64 image

I have this app where I take picture with cordova camera then move it into file-system , save the imgpath for the image into sqlite db and display it, I'm trying to encrypt the imgPath for the image which is saved on ccordova.file.data directory , I tried cordova safe plugin https://github.com/disusered/cordova-safe ,
but I keep getting "Error with cryptographic operation".
Any help would be appreciated
var db = null;
angular.module('starter', ['ionic', 'ngCordova']) 
.run(function($ionicPlatform, $cordovaSQLite) {    
$ionicPlatform.ready(function() {      
try {        
db = $cordovaSQLite.openDB({          
name: "my.db",
          location: 'default'        
});        
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS imageTable " + "(id integer primary key, image text)");      
} catch (e) {        
alert(e);      
} finally {       }
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('ImageCtrl', function($scope, $rootScope, $state, $stateParams, $cordovaDevice, $cordovaFile, $ionicActionSheet, $cordovaCamera, $cordovaFile, $cordovaDevice, $ionicPopup, $cordovaActionSheet, $cordovaSQLite, $interval) {
var imagesP = [];
//$scope.images = [];
$scope.showAlert = function(title, msg) {
var alertPopup = $ionicPopup.alert({
title: title,
template: msg
});
};
$scope.loadImage = function() {
var options = {
title: 'Select Receipts Image ',
buttonLabels: ['Gallery', 'Take photo', 'File System'],
addCancelButtonWithLabel: 'Cancel',
androidEnableCancelButton: true,
};
$cordovaActionSheet.show(options).then(function(btnIndex) {
var type = null;
if (btnIndex === 1) {
type = Camera.PictureSourceType.PHOTOLIBRARY;
} else if (btnIndex === 2) {
type = Camera.PictureSourceType.CAMERA;
}
if (type !== null) {
$scope.selectPicture(type);
}
});
}
// Take image with the camera or from library and store it inside the app folder
// Image will not be saved to users Library.
$scope.selectPicture = function(sourceType) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
correctOrientation: true,
targetWidth: 800,
targetHeight: 800,
popoverOptions: CameraPopoverOptions, // for IOS and IPAD
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
// alert(currentName);
//Create a new name for the photo to avoid duplication
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
//alert(newFileName);
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
$scope.encryptFile(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
// alert( fileEntry.nativeURL);
};
});
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
//$scope.images.push(newFileName);
var imgPath = cordova.file.dataDirectory + newFileName;
$scope.add(imgPath);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
}
},
function(err) {
// Not always an error, maybe cancel was pressed...
})
};
$scope.add = function(path) {             
if (imagesP != null) {          
$cordovaSQLite.execute(db, "INSERT INTO imageTable (images) VALUES(?)", [path] );        
}        
alert("Inserted.");      
},
function(e) {        
alert(e);      
};
$scope.encryptFile = function(file){
var safe = cordova.plugins.disusered.safe,
key = 'someKeyABC';
function success(encryptedFile) {
console.log('Encrypted file: ' + encryptedFile);
}
function error() {
console.log('Error with cryptographic operation');
}
safe.encrypt(file, key, success, error);
}
  
$scope.ShowAllData = function() {     
$scope.images = [];      
$cordovaSQLite.execute(db,"SELECT images FROM imageTable").then(function(res) {          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({                
id: res.rows.item(i).id,
image: res.rows.item(i).images
              
});            
}          
}        
},         function(error) {          
alert(error);        
}      );
 
} 
       

Backbone requireJs has not been loaded yet for context: _

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

Uncaught TypeError: Cannot use 'in' operator to search for 'model' in undefined

i'm learning Backbone.js from the online book 'backbone-fundamentals',
while trying the example i got an error in console related to underscore.js:
Uncaught TypeError: Cannot use 'in' operator to search for 'model' in undefined
i searched for the error on SO what i found as the cause of this error was that i should not pass strings to my model when initializing it. but i didn't.
here is my project, my model:
// models/todo.js
var app = app || {};
app.Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
},
toggle: function() {
this.save({
completed: !this.get('completed')
});
}
});
my collection:
// collections/todos.js
var app = app || {};
var TodoList = Backbone.Collection.extend({
model: app.Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'),
completed: function() {
return this.filter( function( todo ) {
return todo.get('completed');
});
},
remaining: function() {
return this.without.apply(this, this.completed());
},
nextOrder: function() {
if( !this.length ) {
return 1;
}
return this.last().get('order') + 1;
},
comperator: function(todo) {
return todo.get('order');
}
});
app.Todos = new TodoList();
i have two views.
// views/todos.js
var app = app || {};
app.TodoView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#item-template').html() ),
events: {
'dbclick label': 'edit',
'keypress .edit': 'updateOnEnter',
'blur .edit': 'close'
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$el.html( this.template(this.model.attributes) );
this.$input = this.$('.edit');
return this;
},
edit: function() {
this.$el.addClass('editing');
this.$input.focus();
},
close: function() {
var value = this.$input.val().trim();
if( value ) {
this.model.save({ title: value });
}
this.$el.removeClass('editing');
},
updateOnEnter: function(e) {
if (e.which === ENTER_KEY) {
this.close();
}
}
});
and:
// views/app.js
// maybe i should rename this file to appView.js
var app = app || {};
app.AppView = Backbone.View.extend({
el: '.todoapp',
statsTemplate: _.template( $('#stats-template').html() ),
events: {
'keypress .new-todo': 'createOnEnter',
'click .clear-completed': 'clearCompleted',
'click .toggle-all': 'toggleAllComplete'
},
initialize: function() {
this.allCheckbox = this.$('.toggle-all')[0];
this.$input = this.$('.new-todo');
this.$footer = this.$('.footer');
this.$main = this.$('.main');
this.listenTo(app.Todos, 'add', this.addOne);
this.listenTo(app.Todos, 'reset', this.addAll);
this.listenTo(app.Todos, 'change:completed', this.filterOne);
this.listenTo(app.Todos, 'filter', this.filterAll);
this.listenTo(app.Todos, 'all', this.render);
app.Todos.fetch();
},
render: function() {
var completed = app.Todos.completed().length;
var remaining = app.Todos.remaining().length;
if(app.Todos.length) {
this.$main.show();
this.$footer.show();
this.$footer.html(this.statsTemplate({
completed: completed,
remaining: remaining
}));
this.$('#filters li a')
.removeClass('selected')
.filter('[href="#/' + (app.TodoFilter || '' ) + '"]')
.addClass('selected');
} else {
this.$main.hide();
this.$footer.hide();
}
this.allCheckbox.checked = !remaining;
},
addOne: function(todo) {
var view = new app.TodoView({ model:todo });
$('.todo-list').append( view.render().el );
},
addAll: function() {
this.$('.todo-list').html('');
app.Todos.each(this.addOne, this);
},
filterOne: function(todo) {
todo.trigger('visible');
},
filterAll: function() {
app.Todos.each(this.filterOne, this);
},
newAttributes: function() {
return {
title: this.$input.val().trim(),
order: app.Todos.nextOrder(),
completed: false
};
},
createOnEnter: function( event ) {
if( event.which !== ENTER_KEY || !this.$input.val().trim() ) {
return;
}
app.Todos.create( this.newAttributes() );
this.$input.val('');
},
clearCompleted: function() {
_.invoke(app.Todos.completed(), 'destroy');
return false;
},
toggleAllComplete: function() {
var completed = this.allCheckbox.checked;
app.Todos.each(function(todo) {
todo.save({
'completed': completed
});
});
}
});
app.js :
// js/app.js
var app = app || {};
var ENTER_KEY = 13;
var ESC_KEY = 27;
$(function() {
new app.AppView();
});
where should i look when such an error happens?
thank you for your time...
edit:
the error happens when i load the page without doing anything further.
the order of the files is:
<script src="js/models/todo.js"></script>
<script src="js/collections/todos.js"></script>
<script src="js/views/todos.js"></script>
<script src="js/views/app.js"></script>
<script src="js/routers/router.js"></script>
<script src="js/app.js"></script>
the whole error message:
Uncaught TypeError: Cannot use 'in' operator to search for 'model' in undefined
(anonymous function) # underscore.js:5
j.each.j.forEach # underscore.js:5
j.pick # underscore.js:5
Backbone.View # backbone.js:1190
child # backbone.js:1852
(anonymous function) # app.js:9
n.Callbacks.j # jquery.js:2
n.Callbacks.k.fireWith # jquery.js:2
n.extend.ready # jquery.js:2
K # jquery.js:2

Uncaught TypeError: Cannot call method 'observe' of null / Uncaught ReferenceError: Draggable is not defined

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.

Categories

Resources