Getting data with backbone .fetch from a static .json file - backbone.js

Not sure why this isn't working, the app loads fine. I just get the error each time the load function is called without even requesting the json file.
Ive used this same code to load data from a java controller and it works fine, not sure how the static json file is different.
The View:
define([
'jquery',
'underscore',
'backbone',
'validate',
'collections/getBusiness',
'text!templates/home/homeTemplate.html'
], function($, _, Backbone, validate, getBusiness, homeTemplate){
var HomeView = Backbone.View.extend({
el: $("#page"),
events: {
'click #data': 'data'
},
data: function(e) {
getBusiness.fetch({
success: function(r) {
},
error: function(r) {
alert('error!');
}
});
},
render: function(){
this.$el.html(homeTemplate);
}
});
return HomeView;
});
The Model:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var getModel = Backbone.Model.extend({
});
return getModel;
});
The Collection:
define([
'jquery',
'underscore',
'backbone',
'models/getModel'
], function($, _, Backbone, getModel){
var getBusiness = Backbone.Collection.extend({
model: getModel,
url: '../../json/data.json',
sync: function(method, model, options) {
options.timeout = 100000;
options.contentType = "application/json";
options.cache = false;
options.dataType = "json";
return Backbone.sync(method, model, options);
},
parse: function(response) {
return this.result;
},
});
return new getBusiness;
});

Related

How to resolve for angular ui-route

Here is my angularjs code. I have created different routes but i am unable to resolve my contract.dashboard route. If i remove the route object, it works fine but when i tried to reslove something from my service, it dose not work.
(function() {
'use strict';
angular
.module('app.contracts')
.run(appRun);
var _base = {
// Contract Base Contractor
contract: {
controllerAs: 'c',
controller: ['$scope', '$state', 'ContractModel', function($scope, $state, ContractModel){
'ngInject';
var that = this;
$scope.$watch(function(){ return $state.current.data.mode; }, function() { that.mode = $state.current.data.mode; });
that.contract = new ContractModel();
}]
}
};
/* #ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [
{
state: 'contract',
config: angular.extend({
abstract: true,
template: '<contract-manager><ui-view/></<contract-manager>',
url: '/contract'
}, _base.contract)
},
{
state: 'contract.new',
config: angular.extend({
url: '/new',
template: '<contract-editor mode="c.mode" contract="c.contract"></<contract-editor>',
title: 'Contract Editor',
data: {
mode: 'new'
}
}, _base.contract)
},
{
state: 'contract.dashboard',
config: angular.extend({
url: '',
template: '<contract-dashboard></contract-dashboard>',
title: 'Contract Dashboard',
data: {
mode:'dashboard'
},
resolve: {
stubs: function(stubs){
return stubs.service.registerGetCustomers();
}
}
}, _base.contract)
}
];
}
})();

Marionette add grandchild views

I'm building a photo album system with tag functionality. You can tag people in a picture within the album.
I want to build this in Backbone and am trying to set models, collections and views. The models and collections are working with backbone-relational. I managed to show a list with photos, but the problem now is showing the tags in each photo.
How should I do this?
My code so far:
require(['../../common'], function (common) {
require(
["jquery",
"underscore",
"backbone",
"backbone-relational",
"marionette",
"text!templates/phototag.tpl",
"text!templates/tag.tpl",
"pages/fotoalbum/models/album"
],
function($, _, Backbone,Br,marionette,photoTpl,tagTpl,Album) {
items = [
{
'fotonaam':'http://loremipsum.com/300/400',
'tags':
[
{name:'John Doe', 'x':0.5, 'y':0.6},
{name:'Pieter J', 'x':0.5, 'y':0.6}
]
},
{
'fotonaam':'http://loremipsum.com/300/400',
'tags':[
{name:'Hans T', 'x':0.66, 'y':0.2}
]
}
];
var album = new Album( {'photos':items } );
console.log(album);
// vieww
var TagItemView = Backbone.Marionette.ItemView.extend({
tagName: "li",
template: tagTpl
});
var PhotoItemView = Backbone.Marionette.CollectionView.extend({
tagName: "li",
template: photoTpl,
childView: TagItemView
});
var AlbumCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: "ul",
className: "list",
childView: PhotoItemView
});
var myAlbumView = new AlbumCollectionView({'collection':album.get('photos')});
myAlbumView.render();
$('#photolist').append(myAlbumView.el);
});
});
The answer is in Marionette's CompositeView.
This is my new code:
require(['../../common'], function (common) {
require(
["jquery",
"underscore",
"backbone",
"backbone-relational",
"marionette",
"text!templates/phototag.tpl",
"text!templates/taglist.tpl",
"text!templates/tag.tpl",
"pages/fotoalbum/models/album"
],
function($, _, Backbone,Br,marionette,photoTpl,tagListTpl,tagTpl,Album) {
items = [
{
img:'http://loremipsum.com/300/400',
tags:
[
{name:'John Doe', x:0.5, y:0.6},
{name:'Pieter J', x:0.5, y:0.6}
]
},
{
img:'http://loremipsum.com/300/400',
tags:[
{name:'Hans T', x:0.66, y:0.2}
]
}
];
var album = new Album( {'photos':items } );
var tagCollectionView = Backbone.Marionette.CompositeView.extend({
template: tagListTpl,
tagName: "ul",
});
var PhotoCollectionView = Backbone.Marionette.CompositeView.extend({
template: photoTpl,
tagName: "li",
childViewContainer:'.info',
childView: tagCollectionView,
model:this.model,
initialize: function(){
var tags = this.model.get('tags');
this.collection = tags;
this.model = this.model
},
serializeData: function(){
return {
"name": "some value"
}
}
});
var AlbumCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: "ul",
className: "list",
childView: PhotoCollectionView,
});
var myAlbumView = new AlbumCollectionView({'collection':album.get('photos')});
myAlbumView.render();
$('#photolist').append(myAlbumView.el);
});
});

Error with include router in underscore backbone

Trying to use underscore in project with backbone, but receive an error:
Uncaught TypeError: undefined is not a function
In my view, because variable Router undefined. I am new one in backbone and underscore, so please help me, maby something need to change in my code.
main.js
require.config({
paths: {
jquery: 'lib/jquery-2.1.1',
underscore: 'lib/underscore',
backbone: 'lib/backbone',
view: 'view/view'
},
shim: {
'backbone': {
deps: ['jquery','underscore'],
exports: 'Backbone'
}
}
});
require([
'app'
], function(App){
App.initialize();
});
app.js
define([
'router' // Request router.js
], function(Router) {
var initialize = function() {
Router.initialize();
};
return {
initialize: initialize
};
});
router.js
define([
'backbone',
'model/model',
'view'
], function(Backbone, appState) {
var router = Backbone.Router.extend({
routes: {
"": "selected_currency",
"!/": "selected_currency",
"!/finish": "finish"
},
selected_currency: function() {
appState.set({state: "selected_currency"});
},
finish: function () {
appState.set({state: "finish"});
}
});
Backbone.history.start();
return router;
});
/model/model.js
define([
'underscore',
'backbone'
], function(_, Backbone) {
var AppState = Backbone.Model.extend({
defaults: {
currencies: ['USD', 'EUR'],
selected_currency: '',
state: "selected_currency"
},
url: '/site/create-account'
});
return new AppState();
});
view/view.js
define([
'jquery',
'underscore',
'backbone',
'router', // Request router.js
'model/model'
], function($, _, Backbone, Router, appState) {
var Block = Backbone.View.extend({
el: $("#block"),
templates: {
"selected_currency": _.template($('#step_1').html()),
"finish": _.template($('#step_1_complete').html() + $('#step_2').html())
},
events: {
"click button": "get_currency"
},
initialize: function() {
this.model.bind('change', this.render, this);
},
get_currency: function() {
var currency = this.$el.find("[name=currency]").val();
appState.set({selected_currency: currency});
appState.fetch({
data: {'currency': appState.get('selected_currency')},
type: 'POST'
});
appState.once('sync error', function(model) {
this.model.set({"state": "finish"});
}, this);
},
render: function() {
var state = this.model.get("state");
$(this.el).html(this.templates[state](this.model.toJSON()));
return this;
}
});
new Block({model: appState});
var router = new Router();
appState.trigger("change");
appState.bind("change:state", function() {
var state = this.get("state");
if (state == "selected_currency")
router.navigate("!/", false);
else
router.navigate("!/" + state, false);
});
});

Querying on DirectChildrenCount Rally JS SDK

I checked out some other questions posted previously but couldn't find a relevant answer. So here I am posting again: Here's my code:
Ext.create('Rally.data.WsapiDataStore',{
autoLoad: true,
model: 'HierarchicalRequirement',
limit: '500',
fetch: ['ObjectID','DirectChildrenCount','FormattedID'],
filters:[{property: 'DirectChildrenCount', operator: '=', value: 0}], //tried both "0",'0'
listeners: {
load: function(store,data,success){
var data_length = data.length;
console.log("Number = ", data);
}
}
});
Result is an empty array. Furthermore, the result did not contain the field "DirectChildrenCount" at all, even though I am fetching it.
I tried your code without any changes, and it returned 300+ items. DirectChildrenCount was included in the result. It was tested against "2.0rc2" and "2.0rc1" with the same result. Here is screenshot from Chrome's DevTools:
Here is another short app where a grid of stories updated since yesterday is built, filtered by the same condition.
{property: 'DirectChildrenCount', operator: '=', value: 0}
js file is below:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
var millisecondsInDay = 86400000;
var currentDate = new Date();
var startDate = new Date(currentDate - millisecondsInDay);
var startDateUTC = startDate.toISOString();
Rally.data.ModelFactory.getModel({
type: 'UserStory',
success: function(model) {
this.grid = this.add({
xtype: 'rallygrid',
itemId: 'grid',
model: model,
columnCfgs: [
'FormattedID',
'Name',
'Owner',
'LastUpdateDate'
],
storeConfig: {
filters: [
{
property: 'LastUpdateDate',
operator: '>',
value: startDateUTC
},
{
property: 'DirectChildrenCount',
operator: '=',
value: 0
},
]
}
});
},
scope: this
});
console.log('items updated since', startDateUTC);
}
});

Update $scope with $resource

Why is only the one that don't use $resource.get() work? I am using kendo-angular to update. Has this something to do with async? The main variable looks exactly the same so this has to have something to do with $resourse. What am I missing`
This works:
app.controller('SubjectCntrl', ['$scope', 'categoryService', function($scope, categoryService) {
var main = categoryService.getCategories();
var subjects = {
data : [main]
};
$scope.subjects = {
dataSource: subjects
};
}]);
This does not:
app.controller('SubjectCntrl', ['$scope', 'categoryService', 'ApiFactory', function($scope, categoryService, ApiFactory) {
ApiFactory.get(function(categoriesData) {
var main = categoryService.getCategories();
var subjects = {
data : [main]
};
$scope.subjects = {
dataSource: subjects
};
});
}]);
The factory:
app.factory('ApiFactory', ['$resource', function($resource) {
return $resource('http://localhost:8080/rest/forum/categories/1');
}]);
Service:
app.service('categoryService', ['$resource', function($resource){
this.getCategories = function(){
var farmingSubjects = [ {text: "Poteter", spriteCssClass: "subject"}, {text: "Agurk", spriteCssClass: "subject"} ];
var forestSubjects = [ {text: "Tall", spriteCssClass: "subject"}, {text: "Gran", spriteCssClass: "subject"} ];
var animalSubjects = [ {text: "Hundar", spriteCssClass: "subject"}, {text: "Katter", spriteCssClass: "subject"} ];
var farming = { text: "Jordbruk", items: farmingSubjects };
var forest = { text: "Skogshold", items: forestSubjects };
var animals = { text: "Dyrebruk", items: animalSubjects };
var subjects = [farming, forest, animals ];
var main = { text: "Huvudemner", expanded: true, items: subjects};
return main;
};
}]);
Edit: The success function is called without doubt.
ApiFactory.get(function(data){
console.log('success, got data: ', data);
}, function(err){
alert('request failed');
});
I think the second case is not working because you ApiFactory call is failing. The callback you have declared is for success.

Resources