I'm exploring backbone.js framework and I'm interested how can I fetch collection's model from a js object. Let's say I have the following simple application.
<html>
<head>Backbone.js</head>
<body>
<script type="text/javascript">
var data = [{id:1, name: 'Erik'}, {id:2, name: 'John'}]
</script>
<script type="text/javascript">
var Data = Backbone.model.extend({});
var Datas = Backbone.Collection.extend({
model: Data
});
</script>
</body>
</html>
So how can initialize 'Datas' collection from the 'data' object?
see below:
var Data = Backbone.Model.extend({});
var Datas = Backbone.Collection.extend({
model: Data
});
var s = new Datas();
s.add(data);
console.dir(s);
Related
I am trying to pass the JSON output from one view to another view. But I stuck here as I don't know to how move forward. It seems, some event handling, triggers may help. I searched, but I couldn't figured out! I pasted my complete code. Backbone+underscore+jquery front-end with restful back-end. There 5-7 sub-category level. When we print the main category, it should have a hyperlink to navigate to the next sub-category & the sub-category will have links to another level. I successfully got main-category output. Now the main category view has some JSON values to link to the sub-category. I just need some idea on how to pass the JSON value to the another view(sub-category view) to post it to server to get the sub-category list. Hope, it makes clear.
<body>
<div class="page"></div>
<script src="https://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
<script type="text/template" id="user-list-template">
<% _.each(mainCategoryListResponseCollection, function(MainCategoryListResponse) { %>
<p><%= MainCategoryListResponse.get('directoryName') %></p>
<% }); %>
</script>
var MainCategoryListResponse = Backbone.Model.extend({
urlRoot:'/main-dirctory',
defaults:{
"clientCompanyName":"GOD",
"clientCountry":"ALL Country"
"mainCategoryId":"", // This Id from server is used to get the sub-category list
"rootId"":''// This Id from server is used to get the sub-category list
}
});
var MainCategoryListResponseCollection = Backbone.Collection.extend({
model: MainCategoryListResponse,
url: '/main-dirctory'
});
var MainCategoryListView = Backbone.View.extend({
el: '.page',
render: function() {
var that = this;
var mainCategoryListResponseCollection = new MainCategoryListResponseCollection();
// mainCategoryListResponseCollection.set({"typeId": "1"});
mainCategoryListResponseCollection.fetch({
type: 'POST',
data: JSON.stringify({'typeId': '1'}), //Passing the value manually here in the first parent view
contentType: "application/json",
dataType: "json",
success: function (mainCategoryListResponseCollection) {
var template = _.template($('#user-list-template').html(), {mainCategoryListResponseCollection: mainCategoryListResponseCollection.models});
that.$el.html(template);
}
});
}
});
var SubCategoryListView = Backbone.View.extend({
el: '.page',
render: function() {
var that = this;
var subCategoryListResponseCollection = new SubCategoryListResponseCollection();
subCategoryListResponseCollection.fetch({
type: 'POST',
data: JSON.stringify({'???': '???'}), //here I need to pass the dynamic value from the above view. The dynamic value should be like "mainCategoryId": "5", "rootId": "0" which is getting printed in the each loop down here.
contentType: "application/json",
dataType: "json",
success: function (subCategoryListResponseCollection) {
var template = _.template($('#user-list-template').html(), {subCategoryListResponseCollection: subCategoryListResponseCollection.models});
that.$el.html(template);
}
});
}
});
var Router = Backbone.Router.extend({
routes:{
"":"main_directory"
}
});
var MainCategoryListView = new MainCategoryListView();
var router = new Router();
router.on('route:main_directory', function() {
MainCategoryListView.render();
});
Backbone.history.start();
</script>
</body>
I'm having trouble creating an instance of a CollectionView in Marionette 2.4.1. This is a really simple example. Not sure what's going on. Seems like a Marionette bug.
var AppointmentModel = Backbone.Model.extend({
});
var AppointmentCollection = Backbone.Collection.extend({
model: AppointmentModel
});
var TimeSlotView = Marionette.ItemView.extend({
});
var AppointmentCollectionView = Marionette.CollectionView.extend({
childView: TimeSlotView
});
Here is the template:
<script id="time-slot-template" type="text/template">
<div class="col-xs-4">
<button class="btn-time-slot" data-appointment-time="<%= date %>">
<%= date %>
</button>
</div>
</script>
The main code:
//...inside ajax success
// result looks like this:
// [ "2015-1-2", "2015-1-17", "2015-2-1", "2015-2-8" ]
var appointmentCollection = new AppointmentCollection(result.map(function(apt){
return new AppointmentModel({ date: apt });
})); //browser console shows a good valid collection
var appointmentCollectionView = new AppointmentCollectionView({ collection: appointmentCollection });
// Undefined is not a function
What am I doing wrong?
Doesn't look like there's anything wrong with the code you posted.
Can confirm it works fine for me...http://jsfiddle.net/nuewwdmr/
The only change i made was to include the idAttribute in the model but that wouldn't effect this issue you're having.
var AppointmentModel = Backbone.Model.extend({
idAttribute: 'date'
});
The only thing I can think of is that Marionette has dependencies on Babysitter and Wreqr (as well as underscore, Backbone obviously). Have you included these dependencies?
var msg = document.getElementById('inputXML').innerHTML;How to pass input xml as a parameter to web service and displaying response from web service using angular javascript in html.
Here is my code, please help, i m not able to get reponse from web service.
<div ng-app="customerApp" ng-controller="customersController">
<ul>
HI<br><br><li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('customerApp');
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
function customersController($scope, $http, setAsXMLPost) {
var msg = document.getElementById('inputXML').innerHTML;
$http.post("url.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}
</script>
<div id="inputXML">
<ACORD> <SignonRq> <UserId>CUser</UserId> <Password>XuViDgegi/KtGyJuXfuMrw==</Password>
<SignonPswd> <CustId> < </ACORD>
</div>
Because you are not retriving the content of the div. You are simply extracting #inputXML node from the DOM tree. You can try is
var msg = document.getElementById('inputXML').innerHTML;
I am not sure about xml but you are not posting it, use innerHTML to get actual xml from <div id="inputXML">.
inputXML : msg.innerHTML // use innerHTML to get the actual xml
Have you checked if your controller is executing correctly, I think the standard controller declaration would be something like this:
.controller('customersController', ['$scope', '$http', 'setAsXMLPost',function($scope, $http, setAsXMLPost){
var msg = document.getElementById('inputXML').innerHTML;
$http.post("http://nordevd208wa1x.csc-fsg.com/TPOServiceEnh7/TPOService/TPOService.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}]);
in var msg you are getting a javascript object though you need complete html to process so it should be
var = document.getElementById('inputXML').innerHTML;
Also default tranformRequest of $http in angular js is json you will have to change it to text/xml i wrote an article on how you could change it tranformRequest example angularjs
complete example, filename is test.php placed at root
<?php
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
$xmlData = file_get_contents('php://input');
header("Content-type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>' . $xmlData;
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body >
<title>Simple xml post in angularjs Web Application</title>
<meta name="Description" content="Simple xml post in angularjs Web Application">
<div ng-app="customerApp" ng-controller="customersController">
<ul>
<li ng-repeat="x in users">{{x}}</li>
</ul>
</div>
<div id="inputXML">
<ACORD>
<SignonRq><UserId>CUser1</UserId><Password>XuViDgegi/KtGyJuXfuMrw==</Password></SignonRq>
<SignonRq><UserId>CUser2</UserId><Password>XuViDgegi/KtGyJuXfuMrw==1</Password></SignonRq>
</ACORD>
</div> <!-- Libraries -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var app = angular.module('customerApp', []);
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
app.factory(
"getAsXML",
function() {
//prepare the request data for the form post.
function transformResponse(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformResponse);
}
);
function customersController($scope, $http, setAsXMLPost, getAsXML) {
var msg = document.getElementById('inputXML').innerHTML;
$scope.users = [];
$http.post("test.php", msg, {transformRequest: setAsXMLPost, transformResponse: getAsXML}).success(function(returnedXMLResponse) {
//here you will get xml object in reponse in returnedXMLResponse
});
}
</script>
</body>
</html>
I'm having trouble rendering Google Maps (V3) with Backbone.js.
It fails to load when I navigate to map view (/#/map); however, the map somehow loads perfectly fine when I hit refresh in that map view url.
Relevant Code Below:
<body>
Home
<div id="content"></div>
<script type="text/template" id="home_template">
Go !
</script>
<script type="text/template" id="map_template">
<div id="map"></div>
</script>
</body>
var MapView = Backbone.View.extend({
el: '#content',
render: function() {
var template = _.template($('#map_template').html());
var init = function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', init);
this.$el.html(template);
}
});
var Router = Backbone.Router.extend({
routes: {
"" : "home",
"map" : "map"
}
});
var router = new Router;
var homeView = new HomeView();
router.on('route:home', function() {
homeView.render();
});
var mapView = new MapView();
router.on('route:map', function() {
mapView.render();
});
Backbone.history.start();
It seems that 'something' is missing when I'm switching views between home and map, but I'm not sure what that 'something' is. I believe I have combed through relevant questions, but cannot find the missing point.
Any help would be much appreciated.
Thank you!
(P.S The Mapview part is taken from : https://developers.google.com/maps/documentation/javascript/tutorial
)
Problem is here I guess
google.maps.event.addDomListener(window, 'load', init);
you are calling init on window.load, but when you switch between view, it will not refresh the page, and window.load never get triggered. I guess you need to change the way init happening, I could be able to suggest better if I have more information about DOM structure of the page.
I am trying to understand how to handle number of collection instances within my Backbone model. There will be a primary model and that model is composed of multiple instances of collections. The collections themselves are groups of some other model.
Model A
Collection B
Model C
Model C
Collection B
Model C
Model C
Model C
Collection B
Model C
Collection B
might even be empty but will only add more Model C's
Here is the Non-working code...
app.js
(function() {
var App = {};
window.App = App;
var template = function(name) {
return Mustache.compile($('#'+name+'-template').html());
};
App.World = Backbone.Model.extend({
initialize: function() {
var this.continent = new Array();
this.continent[0] = new App.Continent(0);
this.continent[1] = new App.Continent(1);
this.continent[2] = new App.Continent(2);
this.continent[3] = new App.Continent(3);
this.continent[4] = new App.Continent(4);
this.continent[5] = new App.Continent(5);
}
});
App.Continent = Backbone.Collection.extend({
initialize: function(id) {
switch (id) {
case 0:
this.id = "Europe";
case 1:
this.id = "Asia";
case 2:
this.id = "Africa";
case 3:
this.id = "Australia";
case 4:
this.id = "South America";
default:
this.id = "North America";
}
}
});
App.Index = Backbone.View.extend({
template: template('index'),
initialize: function() {
this.world = new App.World();
this.world.on('all', this.render, this);
},
render: function() {
this.$el.html(this.template(this));
return this;
},
bigland: function() {
return this.world;
},
});
App.Router = Backbone.Router.extend({
initialize: function(options) {
this.el = options.el
},
routes: {
"": "index"
},
index: function() {
var index = new App.Index();
this.el.empty();
this.el.append(index.render().el);
}
});
App.boot = function(container) {
container = $(container);
var router = new App.Router({el: container})
Backbone.history.start();
}
})()
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Hello world</h1>
<div id='app'>
Loading...
</div>
<script type="text/x-mustache-template" id="index-template">
<ul>
{{#bigland}}
<li>Hello {{.continent}}</li>
{{/bigland}}
</ul>
</script>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script src="mustache.js"></script>
<script src="app.js"></script>
<script>$(function() { App.boot($('#app')); });</script>
</body>
</html>
the output I am trying to get from this demo
Hello Europe
Hello Asia
Hello Africa
Hello Australia
Hello South America
Hello North America
Questions:
How do I get this code to work using the model with multiple instances of collections.
Is there a better way structure this model? I am open to using backbone plugins for nested models but like to see some working code.
The next level of experimentation is to enable some instances of Collection B to specialize and utilize different business rules. Any thoughts on how to organize this mess like where to put helper methods? Any best practice on where that logic would reside, I could put it in the main model A, inside the Collection B, or elsewhere?
JS Bin link:
http://jsbin.com/ejohom/1/edit
I only explored a different way to structure your Model and Collection. I created a testData structure which would represent how you are loading this data at init time.
Also you will see a continent finder function in the collection.