In Backbone Relational how do I silence add:* events on fetch() - backbone.js

When I load in my model using .fetch() backbone Backbone Relational fires off an add:survey_question for each question it adds (which is the same thing that would happen if load something onto my survey_questions collection via .add(). Even worse, the add:survey_questions dont' respect the comparator on my survey_questions collections.
I would like a way to silence the add:survey_questions that happen
Console.log output when listening to all events on the Survey Model (SurveyBuilder) and Question model (embedded inside a SurveyQuestion model)
//START of .fetch() on the Survey Model
SurveyBuilder
["relational:change:survey_questions", child, Array[3], Object]
app.js:25338
SurveyBuilder
["add:survey_questions", child, child, Object]
app.js:25338
Question
["add:survey_question", child, Backbone.Collection, Object]
app.js:25575
SurveyBuilder
["add:survey_questions", child, child, Object]
app.js:25338
Question
["add:survey_question", child, Backbone.Collection, Object]
app.js:25575
SurveyBuilder
["add:survey_questions", child, child, Object]
app.js:25338
Question
["add:survey_question", child, Backbone.Collection, Object]
app.js:25575
SurveyBuilder
["sync", child, Object, Object]
app.js:25338
//START OF Manual .add()
SurveyBuilder
["add:survey_questions", child, child, Object]
app.js:25338
SurveyQuestion
["change:question_number", child, 4, undefined]
app.js:25578
SurveyQuestion
["change", child, undefined]
app.js:25578
And here are my models:
m.Question = m.BaseModel.extend({
urlRoot: '/api/questions',
initialize: function(){
if(this['type']) {
this.set('type', this['type']);
} else if(this.get('type')) {
this.type = this.get('type');
}
m.BaseModel.prototype.initialize.apply(this, arguments);
},
defaults: {
question_text: '',
question_number: 1,
comment_field: true
},
calculateProperties: function(){
return {
'question_id': this.getID()
};
},
subModelTypes: {
'Numeric': 'APP.Models.NumericQuestion',
'MultipleChoice': 'APP.Models.MultipleChoiceQuestion',
'Checkboxes': 'APP.Models.CheckboxesQuestion',
'FreeText': 'APP.Models.FreeTextQuestion',
'TimePeriod': 'APP.Models.TimePeriodQuestions',
'Sorting': 'APP.Models.SortingQuestion',
'Grading': 'APP.Models.GradingQuestion',
'Slider': 'APP.Models.SliderQuestion',
'AgreeDisagree': 'APP.Models.AgreeDisagreeQuestion',
'YesNo': 'APP.Models.YesNoQuestion'
}
});
m.SurveyQuestion = m.BaseModel.extend({
defaults: {
'question_number': 1
},
relations: [{
type: Backbone.HasOne,
key: 'question',
relatedModel: 'APP.Models.Question',
includeInJSON: '_id',
reverseRelation: {
type: Backbone.HasMany,
key: 'survey_question',
includeInJSON: false
}
}]
});
m.Survey = m.BaseModel.extend({
urlRoot: '/api/surveys',
defaults: {
start_date: moment().format('YYYY-MM-DD'),
end_date: moment().add('weeks', 3).format('YYYY-MM-DD'),
title: moment().format('MMMM') + ' Economist Survey'
},
relations: [{
type: Backbone.HasMany,
key: 'survey_questions',
relatedModel: 'APP.Models.SurveyQuestion',
collectionType: 'APP.Collections.SurveyQuestions',
includeInJSON: true,
reverseRelation: {
key: 'survey',
includeInJSON: true
}
}]
});

Related

How can I Add and Delete nested Object in array in Angularjs

heres my output Image html How can I delete Object in array and push when adding some Data
angular.module('myApp.Tree_Service', [])
.factory('TreeService', function() {
var svc = {};
var treeDirectories = [
{
name: 'Project1',
id: "1",
type: 'folder',
collapse: true,
children: [
{
name: 'CSS',
id: "1-1",
type: 'folder',
collapse: false,
children: [
{
name: 'style1.css',
id: "1-1-1",
type: 'file'
},
{
name: 'style2.css',
id: "1-1-2",
type: 'file'
}
]
}
]
}
];
svc.add = function () {}
svc.delete = function (item, index) { }
svc.getItem = function () { return treeDirectories; }
return svc;
});
})();
I'm Newbee in Angularjs and I don't know how much to play it.
Hopefully someone can help me. Im Stucked.
Well you can delete any object by just usingdelete Objname.property
So for example you want to delete Children in treeDirectories first index object you can use delete treeDirectories[0].children if you want to delete children inside children then delete treeDirectories[0].children[0].children
if you want to remove an index from an array in lowest level children then
treeDirectories[0].children[0].children.splice(index,1)
for pushing data is for object you can directly assign value to the property you want
treeDirectories[0].children[0].newproperty = "check"
And for array you can
treeDirectories[0].children[0].children.push(object)

extjs store.load not populating, possibly root object issue?

I am having trouble loading my first ExtJS store.
var testStore = Ext.data.StoreManager.lookup('myUserStoreID');
testStore.load({
callback: function (records, operation, success) {
testStore.each(function (record) {
debugger;
var task = record.data.description;
console.log(task);
});
//debugger;
//var x2 = operation._response;
//var x3 = x2.responseText;
//var x4 = Ext.decode(x3);
////var x3 = Ext.JSON.decode(operation);
////var x2 = Ext.decode(operation.response);
//console.log(testStore);
}
});
In debugger I can see the correct data if I drilldown into operation._response.responseText, but the records are blank. So I know it just has to do with my code. If I use the Ext.decode it does return an object. What am I doing wrong that the return data automatically populates my store.
Here is a picture of the object in fiddler.
here is the Model I am trying to use... I know it doesn't have all the fields yet.
Ext.define('ExtApplication1.model.UserModel', {
extend: 'ExtApplication1.model.Base',
requires: ['ExtApplication1.model.Base'],
fields: [
/*
The fields for this model. This is an Array of Ext.data.field.Field definition objects or simply the field name.
If just a name is given, the field type defaults to auto. For example:
*/
{ name: 'UserID', type: 'int' },
{ name: 'UserName', type: 'string' },
{ name: 'password', type: 'string' },
{ name: 'Email', type: 'string' },
{ name: 'GroupID' }
],
proxy: {
type: 'ajax',
url: 'http://localhost:49537/api/user/gettargetuser/xxx/xxx',
reader: {
type: 'json',
rootProperty: 'JSON'
}
}
Here is my User class in webapi
here is the MainModel.js where I create stores
Ext.define('ExtApplication1.view.main.MainModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.main',
data: {
name: 'ExtApplication1',
appName: xxx,
appHeaderIcon: '<span class="fa fa-desktop fa-lg app-header-logo">',
footer: 'Copyright - xxx- x
},
stores: {
sessionListByInterest: {
model: 'MainMenuListModel',
autoLoad: false //was true
},
myUserStore: {
model: 'UserModel',
storeId: 'myUserStoreID',
autoLoad: false
},
The issue is that the store expects rootProperty to contain an array of records, while you are only delivering a single record.
If you want to only load a single record, which is not in an array, you would have to use the static model.load() function.
Or you can change your API endpoint from User JSON to List<User> JSON (or IEnumerable<User> or ICollection<User> or User[]...), even if you intend to only return a single user. Doesn't matter how many records there are in the JSON array, but the array is expected by ExtJS store.

Backbone relational one to one relation, how to get parent's model data?

exampleData = {
id: 1,
name: 'A',
house: {
address1: 'California'
address2: 'California'
}
}
House = Backbone.RelationalModel.extend({
urlRoot: function urlRoot() {
var personId = this.get('person').id; // this.get('person') is null
}
});
Person = Backbone.RelationalModel.extend({
relations: [
{ // Create a (recursive) one-to-one relationship
type: Backbone.HasOne,
key: 'house',
relatedModel: House,
reverseRelation: {
type: Backbone.HasOne,
key: 'person'
}
}
],
initialize: function() {
}
});
I need to get the person's model data in House model,
but this.get('person') returns null, even I set up the reverseRelation.
How can I get the Person's data in house?
I think your code will not work. The definition of model is a bit wrong. When you define relation, it should be reference to the object, not the string value:
relatedModel: House // instead of 'House' as a string
Then you may reference through the getters, from each of the models, alike:
houseModel.get("person");
personModel.get("house");

Access Nested Backbone Collection

Below is what i am populating my collection with (FacetModels)
How do I access the AvailableValues[] array
"FacetModels":[
{
"FacetDisplayLabel":null,
"SelectedValues":[],
"AvailableValues":[],
"UnknownResults":0,
"ActionURI":null,
"FacetGroupName":"Category",
"FacetGroupFriendlyId":"SourceCategory",
"FacetGroupOrder":10,
"AllowSuggestions":false
},
This is my view, as you will see all i have access to is the array of FacetModels, I need to be able to pass FacetModels[0].AvailableValues.Name so I can display each category Name
CategoryListItemView = Backbone.View.extend({
tagName: "li",
className: "category",
initialize: function (options) {
this.template = _.template( $("#categorylist_template").html());
},
render: function () {
var category = this.model
console.log(category);
console.log(this.model.toJSON());
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
Display from console
a.Model {cid: "c2", attributes: Object, collection: r, _changing: false, _previousAttributes: Object…}
_changing: false
_events: Object
_pending: false
_previousAttributes: Object
attributes: Object
ActionURI: null
AllowSuggestions: false
AvailableValues: Array[8]
0: Object
ActionURI: "/api/search?firstname=thomas&firstname_variants=true&lastname=smith&region=all&sourcecategory=armed%20forces%20utf0026%20conflict"
Count: 8943
DisplayLabel: "Armed Forces & Conflict"
IsUnknown: false
Name: "Armed Forces & Conflict"
proto: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
length: 8
proto: Array[0]
FacetDisplayLabel: null
FacetGroupFriendlyId: "SourceCategory"
FacetGroupName: "Category"
FacetGroupOrder: 10
SelectedValues: Array[0]
UnknownResults: 0
proto: Object
changed: Object
cid: "c2"
collection: r
proto: Object
Inside your view the javascript array is available through this.model.get('AvailableValues'). If you need Available values to be a Backbone Collection, you can override parse to populate the AvailableValues property with a collection instead of an array.
There are some other SO questions that have examples of this:
backbone-js-fetching-a-more-complex-data-and-using-as-a-collection
how-to-override-backbones-parse-function

relation model between two models: null value

I would like to make a relation between two models User and Task using backbone-relational.
I would like for each Task to get the User model.
The relation between the two model is the following:
taskModel.creator_id = userModel.id
Here is my code (1) (2)
The issue is the following (3):
When I try to fetch the models of task I get for the attributes.user the null value.
(1)
// TaskModel
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: 'HasOne',
key: 'user',
relatedModel: User
}
],
urlRoot: 'url_get_tasks'
});
(2)
// UserModel
var User = Backbone.RelationalModel.extend({
urlRoot: "url_get_users"
});
(3)
user = new User();
user.fetch();
console.log(user.attributes); // {id: 1, .....}
task = new Task();
task.fetch();
console.log(task.attributes); // {id: 12, creator_id: 1, user: null} ???
Why the task.attributes.user have the null value?
Your relation on Task should be something like:
{
type: 'HasOne',
key: 'user',
keySource: 'creator_id',
relatedModel: User
}
(You're expecting it to use creator_id for the association but never told it that.)

Resources