Backbone.Router.extend is giving me the error: "extend" cannot be used on
undefined
Nodejs and express is also used in this project.
but i have not mentioned anythin related to backbone in app.js
Below is my index.html and main.js.
I have a feeling, the jquery,underscore and backbone files may not be loading properly,due to which this error is happening
Kind of beginner in backbone.Any help is greatly appreciated
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="javascripts/jquery.min.js"></script>
<script src="javascripts/json2.js"></script>
<script src="javascripts/underscore-min.js"></script>
<script src="javascripts/backbone-min.js"></script>
<script src="javascripts/main.js"></script>
</head>
<body>
<h1>< title </h1>
<p>Welcome to world of html</p>
</body>
</html>
main.js
$(document).ready(function(){
var Theater = {
Models: {},
Collections: {},
Views: {},
Templates:{},
Routers:{}
}
Theater.Models.Movie = Backbone.Model.extend({});
Theater.Collections.Movies = Backbone.Collection.extend({
model: Theater.Models.Movie,
url: "/json",
initialize: function(){
console.log("Movies initialize")
}
});
Theater.Routers = Backbone.Router.extend({
initialize:function(){ console.log("defaultRoute");},
routes: {
"": "defaultRoute"
},
defaultRoute: function () {
console.log("defaultRoute");
}
});
console.log("gonna call approuter");
var appRouter = new Theater.Routers();
Backbone.history.start();
});
A large number of tiny tweaks and micro bugfixes, best viewed by looking at the commit diff. HTML5 pushState support, enabled by opting-in with: Backbone.history.start({pushState: true}). Controller was renamed to Router, for clarity. Collection#refresh was renamed to Collection#reset to emphasize its ability to both reset the collection with new models, as well as empty out the collection when used with no parameters.
Backbone change log of 0.5.0
http://backbonejs.org/
Backbone's Router was called Controller and renamed to Router when it got version 0.5
Simply replace your Backbone and Underscore files into newer version or use Controller instead. then your code should work.
I strongly recommend to update your Backbone file due to bugs which Backbone used to have.
Related
I have situation where I would like to configure component in html code. I have the following structure.
game.html which is served as in url like example.com/game/7999 which should show page for game 7999.
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>Providence</title>
<script src="/js/angular.js"></script>
<script src="/data-access/data-access.module.js"></script>
<script src="/data-access/data-access.service.js"></script>
<script src="/score-info/score-info.module.js"></script>
<script src="/score-info/score-info.component.js"></script>
<script src="/js/game.js"></script>
</head>
<body>
<div ng-controller="myController">
<p> {{ game_id }} </p>
<score-info game_id="{{ game_id }}"></score-info>
</div>
</body>
Corresponding game.js, which seem to work as game_id shows up correctly.
angular.module('myApp', [
'dataAccess',
'scoreInfo' ],
function($locationProvider){
$locationProvider.html5Mode(true);
});
angular.
module('myApp').
controller('myController', function($scope, $location) {
var split_res = $location.path().split('/');
var game_id = split_res[split_res.length-1];
$scope.game_id = game_id
});
My problem lies in component where I'm unable to inject the game_id. Here's score-info.component.js where the game_id does not become visible.
angular.
module('scoreInfo').
component('scoreInfo', {
templateUrl : '/score-info/score-info.template.html',
controller : function ScoreInfoController(dataAccess) {
self = this;
console.log(self.game_id) // self.game_id == undefined
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
});
},
bindings : {
game_id : '<'
}
});
I noticed that some earlier answers recommended using a separate service of wiring up controller and component. That does not work for me as I need to be able to include varying number of scoreInfo -blocks in a single page.
I'm going to answer this myself. The answer was provided by JB Nizet in comments.
First problem was naming related. The code needs to stick with angular.js' naming convention and use gameId: '<' and use <score-info game-id="game_id">
Also < binding must have the reference in the element without curly braces: <score-info game-id="game_id">
Finally, the components controller needs to take in to the account breaking changes between angular 1.5 -branch and 1.6 -branch. See angular CHANGELOG. Specifically ScoreInfoController becomes
function ScoreInfoController(dataAccess) {
self = this;
self.$onInit = function() {
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
})
}
I have a backend which is generating a json file containing information about the most important pages. I would like to load this json file, and build corresponding states based on the data in the file. I can't inject $stateProvider into .run or .controller, and I can't inject $http into .config, so I am feeling a bit lost.
So the question is. How I can load a json file, go through the data and build states based on this data?
Quick edit: If I am lacking in providing the necessary information, please tell, and I'll try and improve the question.
I've attempted to solve a similar problem and created UI-Router Extras "Future States". Future states tries to solve additional problems, such as lazy loading using RequireJS, placeholders for entire unloaded modules, and routing by bookmarked URL to unloaded placeholders.
Here is a plunk demonstrating how to use Future States for your use case: http://plnkr.co/edit/Ny7MQcmy35dKeEjbw57d?p=preview
I tried using the stackoverflow snippet runner, but had problems, so here is a non-runnable paste of the code.
JS:
// Code goes here
var app = angular.module("jsonstates", ["ct.ui.router.extras"]);
app.config([ '$stateProvider', '$futureStateProvider',
function($sp, $fsp ) {
var futureStateResolve = function($http) {
return $http.get("states.json").then(function(response) {
angular.forEach(response.data, function(state) {
$sp.state(state);
})
})
}
$fsp.addResolve(futureStateResolve);
console.log($fsp);
}]);
app.controller("someCtrl", function() { })
Html:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.2.25" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
<script src="https://rawgit.com/angular-ui/ui-router/0.2.11/release/angular-ui-router.js"></script>
<script src="https://rawgit.com/christopherthielen/ui-router-extras/0.0.10/release/ct-ui-router-extras.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="jsonstates">
<h1>Hello Plunker!</h1>
Top state Nested state
<div ui-view></div>
</body>
</html>
Json:
[
{
"name": "top",
"url": "/top",
"controller": "someCtrl",
"template": "<h1>top state</h1><div ui-view></div>"
},
{
"name": "nested",
"parent": "top",
"url": "/nested",
"controller": "someCtrl",
"template": "<h1>nested state</h1><div ui-view></div>"
}
]
I am new to AngularJS and loving it as I learn it. I am trying to figure out how to communicate with MongoLab from AngularJS using $resource and RESTful API. I have the following two files:
index.html:
-----------
<!DOCTYPE html>
<html lang="en">
<head>
<title>MongoLab Connectivity Test</title>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="app3.js"></script>
<link rel="stylesheet" href="bootstrap.css" />
<link rel="stylesheet" href="bootstrap-theme.css" />
</head>
<body ng-app="myModule">
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
</body>
</html>
app3.js:
--------
var myModule = angular.module('myModule', ['ngResource']);
myModule.controller('display', function($scope, personService) {
$scope.data = personService.query();
});
myModule.constant({
DB_BASEURL: "https://api.mongolab.com/api/1/databases/db1/collections",
API_KEY: "<MyAPIKey>"
})
myModule.factory('personService', ['$resource', 'DB_BASEURL', 'API_KEY',
function($resource, DB_BASEURL, API_KEY)
{
return $resource
(DB_BASEURL+'/persons/:id'
,{id: "#id" apiKey: API_KEY}
);
}
]);
When I try it, I get the following output:
{{data.message}}
I am not sure what I am doing wrong. Hoping to get some help.
A better way to connect would be : https://github.com/pkozlowski-opensource/angularjs-mongolab
[copying the text from documentation AS IT IS]
Usage instructions
Firstly you need to include both AngularJS and the angular-mongolab.js script : https://raw.githubusercontent.com/pkozlowski-opensource/angularjs-mongolab/master/src/angular-mongolab.js
Then, you need to configure 2 parameters:
MongoLab key (API_KEY)
database name (DB_NAME)
Configuration parameters needs to be specified in a constant MONGOLAB_CONFIG on an application's module:
var app = angular.module('app', ['mongolabResourceHttp']);
app.constant('MONGOLAB_CONFIG',{API_KEY:'your key goes here', DB_NAME:'angularjs'});
Then, creating new resources is very, very easy and boils down to calling $mongolabResource with a MongoDB collection name:
app.factory('Project', function ($mongolabResourceHttp) {
return $mongolabResourceHttp('projects');
});
As soon as the above is done you are ready to inject and use a freshly created resource in your services and controllers:
app.controller('AppController', function ($scope, Project) {
Project.all().then(function(projects){
$scope.projects = projects;
});
});
Also, you may check out the blog here for even simpler implementation : http://asad.io/angularjs-with-mongolab/
Use the $http module by Angular and Mongolab REST API
For GET request,
$http.get('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY')
.success(function(data) {
console.log(data)
}
For POST request,
$http.post('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY', $scope.data, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function() {
console.log('Data saved successfully')
}
More on http method support documentation - http://docs.mongolab.com/data-api/#reference
I'm learning Backbonejs and I'm really confused with linking external JS files. So, if I write Backbone script in HTML document between everything works fine. But if I add a link in HTML to JS file it doesn't work. I have tested jQuery in this file and it works fine, it seems like only Backbone.js scripts doesn't work. So, the main question is:
How do I link external JS files where I'm using Backbone.js to my HTML file?
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js"></script>
<script src="testingscript.js"></script>
<title>Backbone for beginners</title>
</head>
<body>
<div id="container">Loading...</div>
<script>
var AppView = Backbone.View.extend({
el: $('#container'),
// template which has the placeholder 'who' to be substitute later
template: _.template('<h3>Hello <%= who %></h3>'),
initialize: function () {
this.render();
},
render: function () {
// render the function using substituting the varibile 'who' for 'world'
this.$el.html(this.template({who: 'world!'}));
}
});
var appView = new AppView ();
</script>
</body>
</html>
Greetings!
There is no special magic to load other js files in the same HTML file that backbonejs is used.
I would make sure that your 'testingscript.js' file is in the right path and get loaded properly. You can look at the console in your web-browser (From FireBug if you use fireFox, or 'Inspect Element' if Chome is used).
Once you confirm that the file is loaded properly, things should work as I don't see you have any unusual in your code.
Good luck!
<script src="testingscript.js"></script>
I want to inject an old style, procedurally built string into a DIV element that's created in a standard ExtJS 4 MVC application, and I'm having a hard time wrapping my head around how I'm supposed to leverage dynamic loading.
So say I have this function by itself in a javascript file called "createHtml.js":
function fillDiv(strDivName) {
document.getElementById(strDivName).innerHTML = "<h1>TEST</h1>";
}
Elsewhere, in my MVC ExtJS 4 app (so in an object referenced within app.js, I have the following:
myPanel = Ext.create('Ext.panel.Panel', {
title: 'Map',
html: '<div style="width:100%; height:100%" id="map"></div>'
});
In my index.html page, I include a reference to createHtml.js. In my app.js file, I have something like the following:
( function() {
Ext.Loader.setConfig({
enabled : true,
paths : {
MyJive: 'media/js/ext/MyCom/MyJive',
}
});
Ext.onReady( function() {
var urlparams = document.URL.split('?')[1];
var param = Ext.urlDecode( urlparams ? urlparams : '' );
var pcard = Ext.create( 'MyJive.view.MyUI',{
param1 : param.param1,
param2: param.param2
});
Ext.create( 'Ext.container.Viewport', {
layout: 'fit',
items: [pcard]
});
});
})();
Now if I attach a listener to a button somewhere on MyUI and have it call fillDiv('map'); I get a Uncaught ReferenceError: fillDiv is not defined error.
If I put fillDiv not in its own file (createHtml.js) but MyUI.js (referenced by pcard, above), I'm golden. So I know it's not a super-stupid issue like having the div id wrong or some wacky, invalid innerHTML value.
I would have thought the app would know about fillDiv() because fillDiv()'s parent file is in index.html's javascript includes, but fine, createHtml.js isn't being dynamically loaded. I've got that, I guess.
But how do I tell app.js that my function exists in a file outside of its bounds?
(Now, "IRL", I've got fillDiv creating a complicated piece of html via OpenLayers so that we can display a map identified by param1 and param2 embedded in the ExtJS form, but I've gone to this simpler setup to try and figure out what I'm doing wrong.)
EDIT: Added index.html. createHtml.js contains the fillDiv() method. Note that the DIV that takes the map isn't in the index.html; it's, again, defined in an ExtJS Panel.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My Project</title>
<link rel="stylesheet" type="text/css"
href="media/js/ext/ext-4.0/css/ext-all.css" />
<link rel="stylesheet" type="text/css"
href="media/js/ext/MyCom/MyJive/css/main.css" />
<script type="text/javascript"
src="media/js/ext/MyCom/MyJive/createHtml.js"></script>
<script type="text/javascript"
src="media/js/ext/MyCom/MyJive/OpenLayers-2.11/OpenLayers.js"></script>
<script type="text/javascript"
src="media/js/ext/ext-4.0/ext-all-debug-w-comments.js"></script>
<script type="text/javascript"
src="media/js/ext/MyCom/MyJive/app.js"></script>
</head>
<body>
<div id="divParent"></div>
</body>
</html>
EDIT: Adding app.js:
( function() {
Ext.Loader.setConfig({
enabled : true,
paths : {
MyProj: 'media/js/ext/MyCom/MyProj',
OpenLayers: 'media/js/ext/MyCom/MapJive/OpenLayers-2.11',
MyComExt : 'media/js/ext/MyCom/MyComExt'
}
});
Ext.onReady( function() {
var urlparams = document.URL.split('?')[1];
var param = Ext.urlDecode( urlparams ? urlparams : '' );
var pcard = Ext.create( 'MyProj.view.MyProj',{
param1: param.p1,
param2: param.p2
});
Ext.create( 'Ext.container.Viewport', {
layout: 'fit',
items: [pcard]
});
});
})();
I would leave just a comment, but I don't have enough points for that.
You didn't include a index.html file with imports of your createHtml.js and app.js files. But the first thing I would check is that your createHtml.js import is placed above app.js.