BackboneJS - this.collection is undefined - json

i have this Backbone View:
define(['backbone','handlebars', 'text!templates/AlphabetList.html'],
function(Backbone,Handlebars, Template) {
'use strict';
var View = Backbone.View.extend({
template: Handlebars.compile(Template),
events: {
'click li':'li_clickHandler'
},
li_clickHandler: function(e) {
var id = $(e.currentTarget).attr('data-id');
Backbone.history.navigate('/category/'+id, {trigger:true});
},
initialize: function () {
},
render: function() {
$(this.el).html(this.template({menu:this.collection.toJSON()}));
return this;
}
});
return View;
}
);
here is my router:
define([
'backbone',
//Views
'views/ArtistTopImage',
'views/AlphabetList',
'collections/AlphabetCollection',
],
function(
Backbone,
AlphabetList,
ArtistTopImage,
AlphabetCollection
) {
'use strict';
var ArtistRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
//Initializing the application
initialize: function () {
var self = this;
//Collections
this.AlphabetCollection = new AlphabetCollection({catId:0});
//Views
this.artistTopImageView = new ArtistTopImage({el:'.ti'});
this.AlphabetList = new AlphabetList({el:'#alphabetical', collection:this.AlphabetCollection});
self.artistTopImageView.render();
this.AlphabetCollection.fetch({success: function(collection) {
self.AlphabetList.collection=collection;
self.AlphabetList.render();
}});
Backbone.history.start({
pushState: false
});
},
//Default route.
index: function () {
var self = this;
},
});
return ArtistRouter;
}
);
And here is my Collection:
define([
"backbone",
"models/AlphabetModel"
],
function(Backbone, AlphabetModel) {
var AlphabetCollection = Backbone.Collection.extend({
model: AlphabetModel,
catId: null,
initialize: function(attrs) {
this.catId=attrs.catId;
},
url: function() {
return "Alphabetical"+this.catId+".json";
}
});
return AlphabetCollection;
});
The HTML template
<ol class="alist">
{{#each menu}}
<li data-id="{{this.url}}">{{this.name}}</li>
{{/each}}
</ol>
and the JSON file:
[
{
"name":"0-9",
"id":"1",
"url":"0"
},
{
"name":"A",
"id":"2",
"url":"1"
},
{
"name":"B",
"id":"3",
"url":"2"
},
{
"name":"C",
"id":"4",
"url":"3"
},
{
"name":"D",
"id":"5",
"url":"4"
}
]
this gives me an error: "this.collection is undefined". I dont know what the problem is, so does someone have an idea?

Related

Vue. Js Laravel count elements of JSON

I would like to display the number of tasks elements in JSON, but I do not know how to go about it.
I want to make something like this:
Tasks to do 2/12 (where 2 - tasks with flag 1, 12 - all tasks)
I tried using the lenght function, but I got the information function lenght is not defined, similarly with the slice function.
[
{
"id":1,
"clients_id":1,
"products_id":1,
"tasks_id":1,
"project_name":"Some project",
"created_at":null,
"updated_at":null,
"clients":{
"id":1,
"client_name":"Some client",
"contact_name":"Some client",
"client_phone":"123123123",
"client_mail":"clientmail#mailclient.com",
"client_nip":"1112223333",
"client_logo":"logo.jpg",
"updated_at":"2019-04-11 09:45:11",
"created_at":"-0001-11-30 00:00:00"
},
"products":{
"id":1,
"product_name":"Some product",
"product_description":"Really nice product bro",
"product_price":"999$",
"updated_at":"2019-04-08 14:35:13",
"created_at":null
},
"tasks":[
{
"id":1,
"project_id":1,
"task_name":"First task",
"task_description":"its very hard task",
"task_due":"2099-01-12 00:00:00",
"status":0,
"created_at":null,
"updated_at":"2019-04-11 14:09:08"
},
{
"id":2,
"project_id":1,
"task_name":"fix task 1",
"task_description":"or something else",
"task_due":"2201-01-12 00:00:00",
"status":1,
"created_at":null,
"updated_at":"2019-04-11 14:10:11"
}
]
}]
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.id = id;
axios.get('/api/v1/projects/' + id)
.then(function (resp) {
app.project = resp.data;
})
.catch(function () {
alert("Could not load your projects")
});
},
data: function () {
return {
//client_id: null,
project: {
id: '',
clients_id: '',
products_id: '',
tasks_id: '',
project_name: '',
updated_at: '',
created_at: '',
clients: ''
},
task: {
status: ''
}
//client: []
}
},
methods: {
saveForm() {
var app = this;
var newproject = app.project;
axios.patch('/api/v1/projects/' + app.id, newproject)
.then(function (resp) {
app.$router.replace('/c/');
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 1;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
},
taskUnDone(taskid, projectid){
var app = this;
{{app}};
var newtask = app.task;
var flag = 0;
axios.patch('/api/v1/tasks/' + taskid + '?status='+flag)
.then(function (resp) {
app.$router.push('/pr/view/' + projectid);
location.reload();
})
.catch(function (resp) {
console.log(resp);
alert("Could not create your company");
});
}
}
}
</script>
You could create a computed function that returns the length of tasks filtered by status of 1.
computed() {
status() {
const tasks = this.project.tasks;
const complete = tasks.filter(task => task.status === 1);
return `${complete.length}/${tasks.length}`;
}
}
Then use status as a "variable" in your markup.
<p>Tasks done: {{ status }}</p>

AngularJS module.factory get remote json

I work on PhoneGap with AngularJS I need some help to get data from remote JSON server. How can I do that in module factory?
My JSON file:
[
{
'name':'',
'number:'',
'department':''
}
]
And my JavaScript:
(function(){
use strict';
var module = angular.module('app', ['onsen']);
module.controller('AppController', function($scope, $data) {
$scope.doSomething = function() {
setTimeout(function() {
ons.notification.alert({ message: 'tapped' });
}, 100);
};
});
module.controller('DetailController', function($scope, $data) {
$scope.item = $data.selectedItem;
});
module.controller('MasterController', function($scope, $data) {
$scope.items = $data.items;
$scope.showDetail = function(index) {
var selectedItem = $data.items[index];
$data.selectedItem = selectedItem;
$scope.navi.pushPage('detail.html', {title : selectedItem.title});
};
});
module.factory('$data', function() {
var data = {};
data.items = [
{
title: 'Noor almosswi',
label: '',
desc: 'Working in Managment',
phone: '0000',
photo:'http://cdn2.hubspot.net/hub/63072/file-14997515-jpg/images/jeremywilcomb_thedanielgroup.jpg?t=1430422772606&width=229&height=229'
},
{
title: 'Safe khalid',
label: '',
desc: 'Working in accounting',
phone: '00000',
photo:'http://localhost/workflow/photos/c0d179d424ae9c327609c5d80e94c6e0_thumb.jpg'
},
{
title: 'Yussif ali',
label: '',
desc: 'Working in Development',
phone: '0000',
photo:'http://www.beyondcareersuccess.com/wp-content/uploads/2012/08/employee.png'
},
{
title: 'Ali kreeam',
label: '',
desc: 'Working in call center',
phone: '000000',
photo:'http://www.piranhaphotography.com/blog/wp-content/uploads/2010/05/brookfield-employee-portrait-photograph-0366.jpg'
}
];
return data;
});
})();
in your factory you can just use
$http.get('url').then(function(data){});
make sure you inject $http as well

ajax call and $.watch in Angular

I need to generate a select menu when a button is clicked. I am making an ajax call to get json data from external file, upon button click. which In turn should update the select with data from json. with the code below the select gets updated only after the button is clicked twice. I am watching the jsonData but its not working as expected.
HTML:
<div ng-controller="MainViewCtrl">
<button ng-click="getDeployedResources()"> Load Resources </button>
<select ng-model="selectedOption.name" ng-options="item.name as item.name for item in jsonData"></select>
</div>
json from dropdown.json:
{
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
},
{
"name": "System",
"type": "project"
},
{
"name": "StratusCommonServices",
"type": "project"
}]
}
}
}
JS:
var app = angular.module('JSONedit', ['ui.sortable'])
.controller('MainViewCtrl', ['$scope', '$http', '$filter','$compile', function ($scope, $http, $filter, $compile) {
$scope.jsonData = {};
$scope.getDeployedResources = function () {
$.ajax({
url: 'json/dropdown.json',
dataType: 'json'
}).done(function (data) {
$scope.jsonData = data.DeployedResources.ResourceList.Resource;
$scope.selectedOption = angular.copy($scope.jsonData[0]);
});
}
$scope.$watch('jsonData', function (json) {
$scope.jsonString = $filter('json')(json);
}, true);
$scope.$watch('jsonString', function (json) {
try {
$scope.jsonData = JSON.parse(json);
$scope.wellFormed = true;
} catch (e) {
$scope.wellFormed = false;
}
}, true);
}])
This is the correct life-cycle of a simple AngularJS Component!
Don't use jQuery for doing something that angular does better!
angular
.module('test', [])
.service('DataService', function($q, $http) {
var self = this;
var mock = {
id: 1,
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
}, {
"name": "System",
"type": "project"
}, {
"name": "StratusCommonServices",
"type": "project"
}]
}
}
};
self.load = function() {
console.log('loading data', mock.id);
for (var i = 0, len = mock.DeployedResources.ResourceList.Resource.length; i < len; i++) {
mock.DeployedResources.ResourceList.Resource[i].name += mock.id;
}
mock.id += 1;
return $q.when(mock);
return $http
.get('/api/data/')
.then(function(result) {
return result.data;
});
}
})
.controller('TestCtrl', function($scope, DataService) {
var vm = $scope;
vm.select = {
current: null,
items: []
};
vm.loadData = function(event) {
console.count('load data');
return DataService
.load()
.then(function(data) {
vm.current = data.id;
return data.DeployedResources.ResourceList.Resource;
})
.then(function(items) {
vm.select.items = items;
vm.select.current = vm.select.items[0];
})
};
vm.loadData();
});
.select-wrapper {
padding: 1em 2em;
background: yellow;
}
.select-wrapper select {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<article ng-app="test">
<div ng-controller="TestCtrl">
<button type="button" ng-click="loadData($event);">LoadNew</button>
<div class="select-wrapper">
<select ng-model="select.current" ng-options="item as item.name for item in select.items"></select>
</div>
<div ng-bind="select.items | json"></div>
</div>
</article>

Problems loading Json via $http using angularJS

I have son problems trying to load a Json in a contact App. (based in angular UI)
I'm new on AngularJS and I don't know where is the error (well, yes, the console sayme 'SyntaxError: Unexpected token i')
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.when("", "/contacts/list");
$urlRouterProvider.when("/", "/contacts/list");
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/contacts/list");
$stateProvider
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: 'contacts.html',
controller: 'contactController',
onEnter: function(){
console.log("enter contacts");
}
})
.state('contacts.list', {
url: '/list',
// loaded into ui-view of parent's template
templateUrl: 'contacts.list.html',
onEnter: function(){
console.log("enter contacts.list");
}
})
.state('contacts.detail', {
url: '/:id',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.html',
controller: function($scope, $stateParams){
$scope.person = $scope.contacts[$stateParams.id];
},
onEnter: function(){
console.log("enter contacts.detail");
}
})
.state('contacts.detail.test', {
url: '/test',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.test.html',
onEnter: function(){
console.log("enter contacts.detail.text");
}
});
});
myapp.controller('contactController',function($scope, $http){
$scope.contacts = []; //declare an empty array
$http.get("contacts.json")
.success(function(response){
$scope.contacts = response; //ajax request to fetch data into $scope.data
});
});
Contents of contacts.json:
[{ id:0, name: "Alice" },
{ id:2, name: "Alirce" },
{ id:3, name: "Alwicse" },
{ id:4, name: "Awlice" },
{ id:1, name: "Bob" }]
I made a Plunkr for explain it well
As everyone's saying in the comments, JSON keys must be strings. Replace contacts.json with
[
{ "id":0, "name": "Alice" },
{ "id":2, "name": "Alirce" },
{ "id":3, "name": "Alwicse" },
{ "id":4, "name": "Awlice" },
{ "id":1, "name": "Bob" }
]
Here's a fixed Plunkr

how to add json to backbone,js collection using fetch

I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON