I'm developing an app with backbone.js, require.js and Phonegap. I'm having problems accessing the Phonegap api from the Model. My index.html file looks like this:
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="topcoat/css/topcoat-mobile-light.min.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<link href="css/pageslider.css" rel="stylesheet">
<script type="text/javascript" src="cordova.js"></script>
<script data-main="js/app" src="js/require.js"></script>
</head>
<body></body>
</html>
In the initialize function of the router, I'm testing the Phonegap API:
initialize: function() {
window.localStorage.setItem("key", "some bloddy value");
var value = window.localStorage.getItem("key");
console.log('the value is');
console.log(value);
}
This works fine, I can get that the value is set and is retrieved. I also have a logged in status model. This is as follows:
define(function (require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
api_key: null,
user_id: null
},
initialize: function () {
window.localStorage.setItem("key2", "some other value");
var value = window.localStorage.getItem("key2");
console.log('in init, the value is');
console.log(value);
},
});
return {
LoginStatus: LoginStatus
};
});
When I call instantiate model from the initialize function of the router, I get the error:
Uncaught illegal access at file:///android_asset/www/js/app/models/loginstatus.js
How can I access Phonegap api from my models?
You should add an event listener to deviceready event. Inside the listener you should start the backbone router. In that way you start using phonegap API when everything is ready.
document.addEventListener("deviceready", function(){
Backbone.history.start();
}, false);
Related
I'm trying to send local notifications for every day at 7 am. I have placed the below code in controller,
Code
function send_push_notification (){
cordova.plugins.notification.local.schedule({
id: 10,
title: "Report",
text: "Pls send a report :-)",
firstAt: alarm_time,
at: at_8_am,
every: "day"
}).then(function (success) {
return true;
}, function (err) {
return false
});
}
But it shows ReferenceError: cordova is not defined.. I have defined
<script src="cordova.js"></script> at very first in my app's index.html file.
I also tried the example given in this http://ngcordova.com/docs/plugins/localNotification/ link. But donno which one to follow. Both are totally different.
Update:
cordova.plugins.notification.local.schedule method only works inside deviceready event listener but not in the controller. I should make it to work on controller..
ie, I have a task of sending local push notification when there is no database update made for that particular date else no need for notification.
The following sample code should get you started in sending local notifications in Android and iOS device.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<h3>Local Notification</h3>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
try {
cordova.plugins.notification.local.schedule({
text: "This is the text.",
at: new Date(new Date().getTime() + 10000)
});
} catch (e) {
alert("Fail " + e);
}
}
The following sample code sends out a test notification on 10th second after launching the app. The code is tested in Android and iOS devices. The above sample code is available in the github page. You can download the sample app, install notification plugin and test the same.
As suggested in my source, the following command could be used to have a forked and modified push plugin to work in your project:
cordova plugin add https://github.com/zxshinxz/PushPlugin.git
The default push plugin needs to be removed and this will be its replacement. If I understood correctly the post below, this solution fixes local notification usage also when the program is turned off.
More info on that linked post.
My source:
Cordova local notification doesn't work while app is in background
Here is a steps for running local notifications on cordova
Step : 1
Type in cmd prompt of your folder
bower install ngCordova
include in your main index.html file before cordova
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
Step:2
Inject dependency
angular.module('myApp', ['ngCordova'])
Install this plugin
cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git
Step:3
Here is schedule.js local notification file used in your controller
(function(){
'use strict';
angular.module('myApp').controller('Schedule',['$scope','$ionicPlatform','$rootScope','$cordovaLocalNotification','$cordovaSms',Schedule]);
function Schedule($scope,$ionicPlatform,$rootScope,$cordovaLocalNotification,$cordovaSms){
//************************Setting Notification***********************
$ionicPlatform.ready(function() {
var now = new Date().getTime();
var _10SecondsFromNow = new Date(now + 10 * 1000);
$cordovaLocalNotification.schedule({
id: 10,
title: 'Report',
text: 'Text here',
at: _10SecondsFromNow
}).then(function (result) {
// ...
});
};
$cordovaLocalNotification.add({
id: 10,
title: 'Report',
text: 'Pls send a report :-)',
firstAt: at_8_am,
every: 'day'
}).then(function (result) {
// ...
});
$scope.scheduleSingleNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
title: 'Title here',
text: 'Text here',
}).then(function (result) {
// ...
});
};
});
//*******************Notification Ended***********************
})();
I need to make an application which alert on the user when the user enters a particular geofenced area. I tried cordova geofencing plugin. But it doesn't work when I enter the area. I don't know what is the problem. Here are my codes.
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function () {
// $log.log('Ionic ready');
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if ($window.cordova && $window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if ($window.StatusBar) {
StatusBar.styleDefault();
}
if ($window.geofence) {
$window.geofence.initialize();
$window.geofence.onTransitionReceived = function (geofences) {
// $log.log(geofences);
if (geofences) {
$rootScope.$apply(function () {
geofences.forEach(function (geo) {
geo.notification = geo.notification || {
title: 'Geofence transition',
text: 'Without notification'
};
// toaster.pop('info', geo.notification.title, geo.notification.text);
});
});
}
};
$window.geofence.onNotificationClicked = function (notificationData) {
$log.log(notificationData);
if (notificationData) {
$rootScope.$apply(function () {
// toaster.pop('warning', 'Notification clicked', notificationData.notification.text);
});
}
};
}
});
})
//Entering Zandig
window.geofence.addOrUpdate({
id: "e941166e-2409-4c97-8c80-14ba9e9d71c9",
latitude: 12.958535143383823,
longitude: 77.6381016522646,
radius: 5,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Reached Zandig";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Leaving Trivandrum
window.geofence.addOrUpdate({
id: "1e473337-4747-4ac3-b921-ccaf572f38ce",
latitude: 8.487695348115592,
longitude: 76.95057034492493,
radius: 3,
transitionType: 2
}).then(function () {
document.getElementById("notification").innerHTML= "Left Trivandrum";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Entering 61
window.geofence.addOrUpdate({
id: "8f8119ce-b577-4f22-9880-57333fcff5de",
latitude: 12.9593547,
longitude: 77.63604520000001,
radius: 5,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Entered 61";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Entering Santhi Sagar
window.geofence.addOrUpdate({
id: "d2c08c58-4f31-44e9-8a5c-8baaae3ebee3",
latitude: 12.960690294723518,
longitude: 77.63856634497643,
radius: 15,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Entered Santhi Sagar";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Leaving Santhi Sagar
window.geofence.addOrUpdate({
id: "6923cf7d-470e-4921-9b54-4516c504cba5",
latitude: 12.960690294723518,
longitude: 77.63856634497643,
radius: 15,
transitionType: 2
}).then(function () {
document.getElementById("notification").innerHTML= "Left Santhi Sagar";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Getting watched from device
window.geofence.getWatched().then(function (geofencesJson) {
var geofences = JSON.parse(geofencesJson);
});
//Listening for Geofencing transitions
window.geofence.onTransitionReceived = function (geofences) {
geofences.forEach(function (geo) {
alert('Geofence transition detected');
console.log('Geofence transition detected', geo);
});
};
//When click on notification
window.geofence.onNotificationClicked = function (notificationData) {
Alert('Geofencing is Working');
console.log('App opened from Geo Notification!', notificationData);
};
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Geofencing</h1>
</ion-header-bar>
<ion-content>
<p id="notification"></p>
</ion-content>
</ion-pane>
</body>
</html>
(In the Github page of the plugin, there was an option that 'unique id for geofence'. I added the unique id from UUID generator online page.)
But no alert is displaying. Can anyone help?
When I run using ionic serve, in the console, the following error found. 'Uncaught TypeError: Cannot read property 'addOrUpdate' of undefined'.
Here is my console errors with device.
0 466310 error Uncaught TypeError: Cannot read property'addOrUpdate' of undefined, htttp://192.168.43.148.8100/js/app.js, Line 28
1 466870 error No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.
2 466930 error Uncaught TypeError: object is not a function, http://192.168.43.148:8100/plugins/cordova/plugin-geofence/www.geofence.js, Line 119
Can anyone help me?
Here is a ionic sample project from authors of same plugin : https://github.com/cowbell/ionic-geofence , in it you can see total guide of how to use it in ionic. Your code should also work but you are doing few mistakes.If you want to run some plugin related code at initialization of application, put them into .run() part, you are using plugin calls out of that. Plus no need to use document.addEventListener('deviceready') as you have $ionicPlatform.ready, initialize plugin in that. Your code will be like this
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
//Use your plugin related calls in this area
})
});
You were getting error of undefined because you were making plugin calls before even their object was available to application.Again, any plugin related calls which you want to run at time of initialization, use them in $ionicPlatform.ready(function() {}) .
so I see you said you tested it using ionic server. you cant test plugins via the browser, you have to actually install it on the device in order to test cordova plugins. You can also test most plugins via emulation using the intel xdk. https://software.intel.com/en-us/intel-xdk just import your project and emulate it then move to your geofenced location via the map on the right. Or you can hit the test tab and push it to a phone and test it using the intel app preview app on your iphone or android device. Last but not least you can use the debug tab to push it straight to a device using a usb cable and this will allow you to have a debugging console while you test the plugin on your device.
I am trying to test an Ext JS 5.0.1 application with Jasmine 2.3.4. I keep getting the error "Uncaught ReferenceError: describe is not defined". It is as though it is not seeing describe, it, and other global functions. If I switch out the Jasmine files to 1.3, then it does see these global functions. I want to use the newest version of Jasmine and furthermore, I am not sure 1.3 plays well with Ext JS 5. Has anyone else run into this issue? Code snippets below:
specrunner.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Application</title>
<!--Jasmine Files -->
<link rel="stylesheet" type="text/css" href="/app_name/app/js/jasmine/jasmine.css">
<script type="text/javascript" src="/app_name/app/js/jasmine/jasmine.js"></script>
<script type="text/javascript" src="/app_name/app/js/jasmine/jasmine-html.js"></script>
<!-- ExtJS Files -->
<script type="text/javascript" src="//cdn-tst.corporate.com/LNF/4/4.0.1/extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="//cdn-tst.corporate.com/LNF/4/4.0.1/extjs/packages/ext-theme-classic/build/ext-theme-classic.js"></script>
<!-- Jasmine Test Case File -->
<script type="text/javascript" src="/app_name/app/js/spec/AppSpec.js"></script>
<!-- app Test Case File -->
<script type="text/javascript" src="/app_name/app/js/test/app.js"></script>
</head>
<body>
</body>
</html>
app.js (for testing)
Ext.Loader.setConfig ({enabled: true});
// Loading different components like controller, model, view..
Ext.application ({
models: [ 'Trip' ],
stores: [ 'Trips' ],
// views: [ 'simpleTrip' ], Views are throwing an error
autoCreateViewport: false,
name: 'carrier360',
// using the Launch method of Application object to execute the Jasmine Test Cases
launch: function () {
debugger;
var jasmineEnv = jasmine.getEnv ();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter ();
jasmineEnv.addReporter (htmlReporter);
jasmineEnv.execute ();
}
});
AppSpec.js
describe ("ExtJS App Test Suite", function () {
debugger;
beforeEach (function () {
// Initializing the mainPanel
debugger;
tripsStore = Ext.StoreManager.lookup ('Trips');
simpleTrip = Ext.create ('app.view.simpleTrip');
controller = Ext.create ('view.controller.tripController');
});
/* Test if View is created Successfully.*/
it ('View is loaded', function () {
debugger;
expect (simpleTrip != null).toBeTruthy ();
});
/* Test if store is loaded successfully.*/
it ('Store shouldn’t be null', function () {
debugger;
expect (tripsStore != null).toBeTruthy();
});
/* Test controller is initialized successfully.*/
it ('Controller shouldn’t be null', function () {
debugger;
expect (controller != null).toBeTruthy();
});
});
Any suggestions on why describe and other functions are not visible would be appreciated!
Descibre, it, ... are no longuer defined in jasmine.js but instead in the boot.js included with jasmine library.
I am having trouble setting up ng-view. This is my first mean stack app. I got everything working within index.html. However, when I set up ng-view I am getting errors stating that I have my javascripts in a public folder. My index.html is in the html folder. I have set up an additional folder in views called templates to house my additional pages
"GET http://localhost:3000/templates/home.html 500 (Internal Server Error)"
Inside of my html I have set up ng-view
<!doctype html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Caffeine app</title>
<!-- styles -->
<link href="http://netdna.bootstrapcdn.com/bootswatch/3.3.2/yeti/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="stylesheets/style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container>
<div ng-view>
</div>
</div>
<!-- scripts -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<script src="javascripts/main2.js" type="text/javascript"></script>
</body>
</html>
In my public js folder I have set up my factory, config, and controllers. I am using swig.
var app = angular.module('myApp', ['ngRoute'], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
app.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/home',{
templateUrl:'templates/home.html',
controller:'myController'
})
.when('/drinkLibrary',{
templateUrl:'templates/drinkLibrary.html',
controller:'DrinkLibraryController'
})
.otherwise({
redirectTo: '/home'
})
$locationProvider.hashPrefix('!');
});
app.factory('Drink',function($http) {
var Drink = function(name,description,caffeineLevel) {
this.name = name;
this.description = description;
this.caffeineLevel = caffeineLevel;
}
return Drink;
})
app.controller('HomeController',function($scope){
console.log('home');
})
app.controller('DrinkLibraryController',function($scope){
console.log('drinkLibrary');
})
app.controller('myController', function($scope,Drink,$http ) {
var init = function() {
$scope.defaultForm = {
beverageName: "",
description: "",
caffeine: ""
};
}
init();
// $scope.defaultForm = defaultForm;
$scope.allDrinkList = [];
$scope.drinkList= function(obj) {
var newdrink = new Drink(obj.beverageName,obj.description,obj.caffeine);
$scope.allDrinkList.push(newdrink);
console.log($scope.allDrinkList);
init();
$http.post('/api/drinks',obj).
success(function(data){
console.log(data)
$scope.message = 'success';
}).
error(function(data){
console.log('error');
})
};
});
Inside of my routes folder I am making sure to render the index
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
In doing a mean stack I must remember to set up routes on the server and client side. My templates are in the view. I am rendering my view through express I need to also render my templates in the same manner.
app.use('templates/:templateid', routes);
I am using the express generator so through the routes I called a get request and set the url to the templates folder. Next, I identified the template id as a param. This saves me from setting up each page ex(home,library, about).
router.get('/templates/:templateid' ,function(req,res,next){
res.render('templates/' + req.params.templateid);
})
Im trying to create a simple application using backbone..
When i am trying to run my code,this error shows
Failed to load resource: the server responded with a status of 404
(Not Found) users.
What this program really does is, just call the router.js file and render a simple html..
Please help me to clear the error..
If i use ajax prefilter then no errors and also no output.
Im using eclipse and tomcat server7.
And also my important question is
How to use a RESTful Api in a Backbone program and give me a sample
program?
Here is my code..
My HTML code:
<html>
<head>
<meta charset="utf-8">
<title>Welcome Backbone</title>
</head>
<body>
<div class="container">
<h1>User Manager</h1>
</div>
<div class="page"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"
type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"
type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"
type="text/javascript"></script>
<script type="text/javascript" src="js/router.js"></script>
</body>
</html>
My js code:
/**
* New node file
*/
/* $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.url='http://localhost:8080/PageProject/#'+options.url;
console.log(options.url);
}); */
var Users = Backbone.Collection.extend({
url: '/users'
});
var UserList = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var users1 = new Users();
users1.fetch({
success: function () {
that.$el.html('!CONTENT SHOULD BE HERE');
console.log('request reached');
}
});
}
});
var Router = Backbone.Router.extend({
routes: {
'': 'home'
}
});
var UserList = new UserList();
var router = new Router();
router.on('route:home', function () {
console.log('Welcome Backbone!');
UserList.render();
});
Backbone.history.start();