Backbone.js - unable to get the model inside the filter function - backbone.js

In my project i am returning a data using filter method, out of filter i am getting the object, but inside the filter getting as undefined...
they way i doing is wrong..? any one guide me please?
my complete code :
var taskListGenerator = function(params){
var taskListPhraseI = {},
column=params.column,
leftSpine=params.leftSpine,
topSpine = params.topSpine;//workspace to phrase one;
taskListPhraseI.model = Backbone.Model.extend({
url : 'data/data.json',
defaults:{
"id" :"id",
"title" :"Title",
"projectName" :"project",
"dueDays" :0,
"dueTime" :0,
"dueDate" :"0-0-0000",
"totalTasks" :0,
"taskCompleted" :0,
"percent" :65,
"taskStatus" :"Assigned",
"jobtype" :"vip",
"username" :"scott.pierce#groupfmg.com",
"notes" :"notes1"
}
});
taskListPhraseI.collection = Backbone.Collection.extend({
model:taskListPhraseI.model,
url : 'data/data.json',
resetWithFilter : function(data,type) {
var filtered = data.models.filter(function (item) {
return item.get("dueDays") === type;
});
return filtered;
}
});
taskListPhraseI.oneView = Backbone.View.extend({
template:$('#boardTemplate').html(),
render:function(){
var temp = _.template(this.template);
return temp(this.model.toJSON());
}
});
taskListPhraseI.allView = Backbone.View.extend({
el:$('.boardHolder'),
events:{
'click span.green' : 'filterIt'
},
initialize:function(){
var that = this;_.bindAll(this);
this.collection = new taskListPhraseI.collection();
this.collection.fetch({success:that.render});
this.on('change:filterType', this.setNewType);
//this.on('reset:filterType', this.setNewType);
},
setNewType:function(){
var newCollection = new taskListPhraseI.collection();
newCollection.fetch({context:this,update:true})
.done(function(){
this.collection.reset(newCollection,{ silent: true })
var values = newCollection.resetWithFilter(newCollection,this.filterType);
this.render(values);
});
},
filterIt:function(e){
this.filterType = parseInt($(e.target).text());
this.trigger('change:filterType');
},
localVariable:{
numElement:0,
modelSize:0,
stepElement:$('.stepValue'),
stepRange : $('.stepRange'),
stepWidth:0,
compoundWidth:0,
viewProter : $('.stepRangeCompound')
},
render:function(data){
this.localVariable.modelSize = this.collection.models.length;
console.log(data) // first time work fine, while it work on click event, show the error
_.each(data.models, function(item){
this.renderBoard(item)
},this);
},
renderBoard:function(item){
var singleView = new taskListPhraseI.oneView({model:item}),
board = this.$el.append(singleView.render()),
newBoard = board.find('.indBoard:last');
this.positionBoards(newBoard);
},
positionBoards:function(tag){
var prop = this.localVariable,
boardWidth = tag.outerWidth(),
boardHeight = tag.outerHeight(),
topVal = prop.numElement % column,
lftVal = Math.floor(prop.numElement / column),
holderWidth = 0;
prop.stepWidth = boardWidth,
prop.compoundWidth = $('.stepRangeCompound').width();
this.$el.css({
height: (boardHeight+topSpine) * column,
width : Math.ceil((prop.numElement+1) / column) * (boardWidth+leftSpine),
});
holderWidth = this.$el.width();
if(holderWidth <= prop.compoundWidth){
$('.stepRange').hide();
}else{
$('.stepRange').show();
}
tag.css({
left:(boardWidth * lftVal) + (lftVal * leftSpine),
top:boardHeight * topVal + (topVal* topSpine),
});
prop.numElement++;
if(prop.modelSize === prop.numElement){
this.initStepScroll();
}
},
initStepScroll:function(){
var prop = this.localVariable,
stepNavi = prop.stepElement,
stepMin = stepNavi.find('.stepMin'),
stepMax = stepNavi.find('.stepMax'),
stepHandler = prop.stepRange,
maxScrollable = this.$el.width() - prop.compoundWidth,
accomadable = Math.floor(prop.viewProter.width() / prop.stepWidth),
showing = accomadable * column <= prop.modelSize ? accomadable * column : prop.modelSize,
startVal = 0,
that = this;
stepMax.text(prop.modelSize);
stepMin.text(showing)
var slideElement = stepHandler.slider({
min:0,
max:maxScrollable,
step:prop.stepWidth,
slide:function(i,ob){
startVal = Math.abs(parseInt(that.$el.css('marginLeft')));
that.$el.css({
marginLeft:-ob.value
});
var currVal = Math.abs(parseInt(that.$el.css('marginLeft')));
var dir = startVal < currVal ? 1 : startVal > currVal ? -1 :'';
showing += dir * column
var update = showing > prop.modelSize ? prop.modelSize : showing;
stepMin.text(update);
}
});
slideElement.find('.ui-slider-handle')
.wrap(
$('<div />').css({
position:'relative',
marginRight:slideElement.find('.ui-slider-handle').width(),
height:'100%'
})
);
}
});
var boards = new taskListPhraseI.allView();
}
Json sample :
{
"id" :1, "title" :"Title1",
"projectName" :"project1", "dueDays":7,
"dueTime":2.45, "dueDate":"12-12-2010",
"totalTasks" :15, "taskCompleted" :10,
"taskStatus" :"Assigned", "jobtype"
:"vip", "username"
:"scott.pierce#groupfmg.com", "notes"
:"notes1"
}
error:
undefined
tasklist.js (line 33)
TypeError: item is undefined
Thanks in advance

i converted my array return from filter in to collection, sending back to collection method like this.. it work correctly
setNewType:function(){
var newCollection = new taskListPhraseI.collection();
newCollection.fetch({context:this,update:true})
.done(function(){
var values = new taskListPhraseI.collection(newCollection.resetWithFilter(newCollection,this.filterType));
// send back to collection to convert array became collections, it solves the issue.
this.render(values);
});
},
thanks all.

Related

Isotope: Combined multiple checkbox and searchbox filtering

I'm trying to combine the Isotope multiple checkbox filtering with a searchbox.
I used the example with the checkbox filters from here and tried to implement the searchbox but with no luck.
Just the checkbox filtering works well. I think i'm close to the solution but my javascript skills are at a very beginner level.
I commented out the section of what i've tried to implement.
Thank you for some hints
// quick search regex
var qsRegex;
var $grid;
var filters = {};
var $grid = $('.grid');
//set initial options
$grid.isotope({
layoutMode: 'fitRows'
});
$(function() {
$grid = $('#grid');
$grid.isotope();
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
/*var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
var filterResult = function() {
return comboFilter && searchResult;
}*/
$grid.isotope({
filter: comboFilter //or filterResult
});
});
});
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, ));
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
threshold = threshold || 100;
return function debounced() {
clearTimeout(timeout);
var args = arguments;
var _this = this;
function delayed() {
fn.apply(_this, args);
}
timeout = setTimeout(delayed, threshold);
}
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).prop('checked', false);
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.parents('.option-set').find(selector).prop('checked', false);
}
}
I found the solution by myself, but i had to add a second function for returning the searchresult. Otherwise the search function is triggered only after using a checkbox or leaving the search box input field.
How could i avoid this redundand code?
JS:
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, 200));
$(function() {
$grid = $('#grid');
$grid.isotope({
filter: function() {
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return searchResult;
}
});
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$grid.isotope({
filter: function() {
var buttonResult = comboFilter ? $(this).is(comboFilter) : true;
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return buttonResult && searchResult;
}
});
});
});

Single text box search in ng-table

I am using ng-table for users listing in my app.
This is my table, I can single field a time. But I want to search multiple keys with single field
I have a array of values var search = ['Suhail', 'User'];
I want to search this array in data
Eg:- Suhail,User Like
function getUsers(params) {
var data = { page: params.page(), count: params.count() };
if (!users.length) {
var getUsersCallBack = userService.getUsers(data);
return getUsersCallBack.then(function (response) {
var responseJson = angular.fromJson(response.data);
vm.out = responseJson.data;
users = vm.out.invitations.concat(vm.out.users);
users.forEach(function (user, index) {
user.statusName = status[user.status];
user.invitation = (index < vm.out.invitations.length) ? "Pending" : "Accepted";
user.roleName = vm.userRoles[user.role];
}, this);
vm.tableBasic.total(users.length);
var orderedData = vm.search ? $filter('filter')(users, vm.search) : users;
vm.resultNotFound = orderedData.length ? false : true;
return (orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
});
}
else {
var searchArr = vm.search.$.split(";");
var orderedData = vm.search ? $filter('filter')(users, vm.search) : users;
vm.resultNotFound = orderedData.length ? false : true;
vm.tableBasic.total(orderedData.length);
return (orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
}
vm.tableBasic = new NgTableParams({
page: 1,
count: 5
}, {
counts: [],
filterDelay: 300,
getData: getUsers
});
Just use in-build $filter of angular.
You have object with all table data. Apply angular filter on that variable and then show the response in table.
$scope.loadTable = function(){
$scope.data = $scope.searchText ? $filter('filter')($scope.table_data, $scope.searchText) : $scope.table_data;
$scope.tableParams = new NgTableParams({},{dataset: $scope.data});
}
$scope.clearSearch = function(){
$scope.searchText = '';
$scope.loadTable();
}
Here loadTable function is called on submitting Search button and clearTable function is called on clearing the filter and reloading the table data.

NgTable using API and groupBy with a global filter

I'm having difficulty with NgTable, however the functionality I'm looking for may be a limitation on the table framework.
I'm using an API call within the getData, and the data is being grouped (via the groupBy property in the settings param).
I want to be able to use a global filter on the data, I can't seem to get it work with grouping. There's two examples, except they don't mix:
Grouping: http://ng-table.com/#/grouping/demo-grouping-basic
Global filtering: http://ng-table.com/#/filtering/demo-api
Any suggestions?
Table declaration/config
$scope.tableNotesParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page: use total result set in this case,
sorting: {
created_at: 'desc'
}
}, {
groupBy: function( note ) {
return moment( note.created_at ).format( 'YYYY' );
},
getData: function ( $defer, params ) {
$scope.request.notes.state = 'started';
$scope.request.notes.notesSpinner = true;
var offset = params.count() * ( params.page() - 1 );
// Default
var urlQueryParams = {
'email': member.accounts.email,
'offset': offset,
'limit': params.count() || 10
};
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
$scope.notes = results.data;
$scope.noteMembers = extractionService.getAllUniqueMembers( $scope.notes );
// Get the range values, expecting value to be: items 1-10/655
var noteHeaders = results.headers();
var notesRangeValues = noteHeaders['content-range'].match( /(\d{1,})/g );
$scope.tableNotesMetaData = {
offsetStart: notesRangeValues[0] || 0,
offsetEnd : notesRangeValues[1] || 0,
totalCount : notesRangeValues[2] || 0
};
// Update parent controller count
$scope.tabs.notes.count = notesRangeValues[2] || 0;
// Update the total
params.total( $scope.tableNotesMetaData.totalCount );
var orderedData = params.sorting() ?
$filter('orderBy')($scope.notes, params.orderBy()) :
$scope.notes;
$defer.resolve( orderedData );
$scope.request.notes.state = 'completed';
$scope.request.notes.notesSpinner = false;
});
}
});
Edit:
The filtering example for a global filter doesn't do anything to the grouped data:
function applyGlobalSearch(){
var term = self.globalSearchTerm;
if (self.isInvertedSearch){
term = "!" + term;
}
self.tableParams.filter({ $: term });
}
I don't think it's performant to query your notesApiService.getNotes() in the getData()-function, but whatever. Since we don't have the HTML or a JSBin to work with, it's mostly guestimate:
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
var term = $scope.globalSearchTerm.toLowerCase();
if (term.length == 0) {
$scope.notes = angular.copy(results.data, []);
} else if (term.length > 1) {
$scope.notes = results.data.filter(function(item) {
var val = JSON.stringify(item).toLowerCase();
return (val.indexOf(term) != -1);
});
}

Can't $update or $set ~ "undefined is not a function" ~ AngularFire

What I'm trying to do:
Update the status to "TAKEN" when the chat is closed.
Issue:
Can't get $scope.currentChat.$set() or $scope.currentChat.$update() to work when trying to update the status. (See the $scope.close() function.)
What I've tried:
Various methods including $set, $update; I don't know. A lot of things. Been researching this for several hours, and can't find a solution that works.
NOTES:
$scope.currentChat.$set({status:"TAKEN"}); Doesn't work.
$scope.currentChat.$getRecord('status'); Works. Returns:
Object {$value: "OPEN", $id: "status", $priority: null}
So what exactly is going on here? Why can't I seem to set the status to TAKEN?
The issue is currently in the $scope.close() function, when trying to update the status:
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
Here's my code:
bloop.controller('HomeCtrl', ['$scope', '$firebase', function($scope, $firebase) {
console.log("HomeController!");
var url = 'https://**********.firebaseio.com/tickets/';
var ref = new Firebase(url);
// $SCOPE.CREATETICKET
// - This function makes a connection to Firebase and creates the ticket.
$scope.createTicket = function() {
$scope.tickets = $firebase(ref).$asArray();
$scope.tickets.$add($scope.ticketObject).then(function(r) {
var id = r.name();
$scope.currentFBID = id;
$scope.syncTickets();
console.log("===========================");
console.log("CREATED TICKET: " + $scope.currentFBID);
console.log("URL: " + url + $scope.currentFBID);
console.log("===========================");
});
}
// $SCOPE.SYNCTICKETS
// - This function makes a connection to Firebase and syncs the ticket with the $scope to easily update the tickets.
$scope.syncTickets = function() {
var ticketRefURL = new Firebase(url + $scope.currentFBID);
$scope.currentChat = $firebase(ticketRefURL).$asArray();
$scope.currentChat.$save($scope.ticketObject);
var archiveRefURL = new Firebase(url + $scope.currentFBID + "/archive");
$scope.currentChat.archive = $firebase(archiveRefURL).$asArray();
console.log("===========================");
console.log("SAVED TICKET: " + $scope.currentFBID);
console.log("URL: " + ticketRefURL);
console.log("ARCHIVE URL: " + archiveRefURL);
console.log("===========================");
}
// $SCOPE.POST
// - This function pushes whatever is typed into the chat into the chat archive.
// - $scope.ticketObject.archive (is an array of objects)
$scope.post = function(name) {
// Push to ticketObject.archive array...
$scope.ticketObject.archive.push({
"name" : name,
"text" : $scope.chatText
});
// Logging the array to make sure it exists...
console.log("===========================");
console.log("CHAT ARCHIVE:");
console.log($scope.ticketObject.archive);
console.log("===========================");
$scope.currentChat.archive.$add({
"name" : name,
"text" : $scope.chatText
});
// This resets the text area so it's empty...
$scope.chatText = "";
} // WORKS
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
// $SCOPE.TOGGLE
// - This function toggles the chat to be either open or closed.
$scope.toggle = function() {
if($scope.toggleState === false) {
$scope.toggleState = true;
$scope.checkTicket();
} else if($scope.toggleState === true) {
$scope.toggleState = false;
}
}
// $SCOPE.CHECKTICKET
// - This function checks to see if there's an existing ticket.
// - If there's not an existing ticket, it creates one.
$scope.checkTicket = function() {
if($scope.ticket === false) {
// Generate New Ticket Data
$scope.ticketObject = newTicket();
// Create the Ticket
$scope.createTicket();
// Ticket now exists.
$scope.ticket = true;
}
}
function newTicket() {
var ticketID = generateTicketID();
var newTicket = {
id: ticketID,
status: "OPEN",
name: "N/A",
email: "N/A",
date: generateDate(),
opID: "Unassigned",
opName: "Unassigned",
archive: [],
notes: []
}
return newTicket;
}
function generateTicketID() {
var chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var result = '';
for(var i=12; i>0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
function generateDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
dd = '0' + mm;
}
var date = mm + "/" + dd + "/" + yyyy;
return date;
}
}]);
$update and $set are part of the $firebase API. You are attempting to call them on the synchronized array returned by $asArray(), which is a $FirebaseArray instance. That has its own API, which includes neither update nor set.

ExtJs 4.2 Extend Custom Model using MVC problems

Using ExtJs 4.2 with MVC pattern
I am trying to make a custom model, store, proxy, reader, writer but am having problems getting it to work in the MVC pattern. I followed this example to extend a model and I can see it working only if it is not used in the MVC way.
My store refers to a model such as Contacts defined in the model property, then Contacts refers to custom model WakandaModel using the model property. But when I create my store which refers to Contacts none of the model properties or proxy defined in the custom WakandaModel is brought over to the stores model.
Here is my code, I have left comments in so you can see what I have attempted to try. Thanks for any help!
App Code
Ext.Loader.setConfig({
enabled : true,
paths : {
'Ext.ux' : "lib/extux",
'Wakanda' : "lib/extux/wakanda"
}
});
Ext.application({
name : 'SimplyFundraising',
autoCreateViewport : true,
requires : ['Ext.ux.Router', // Require the UX
'Ext.window.MessageBox'],
controllers : ['Contacts'],
});
Custom Model
Ext.define('Wakanda.Model', {
extend: 'Ext.data.Model',
idProperty: '__KEY',
stampProperty: '__STAMP',
defaultProxyType: 'wakanda',
onClassExtended: function(cls, data) {
// debugger;
// cls.apply(this)
// var parts = data.$className.split('.');
// var entity = parts[2]
// var catalog = this.prototype.getCatalog(entity),
// attributes = catalog.attributes;
// for (var i = 0, l = attributes.length; i < l; i++) {
// if (attributes[i].name === 'ID') {
// attributes[i].persist = false;
// }
// }
// attributes.push({name: this.prototype.idProperty});
// attributes.push({name: this.prototype.stampProperty});
// // data.fields = attributes;
// // debugger;
// //this.setFields(data.fields)
// // var mymodel = Ext.ModelManager.getModel(data.$className);
// debugger;
// Ext.appy(this);
// //this.superclass.superclass.$onExtended.apply(this, arguments);
},
getCatalog: function(className) {
var catalog;
Ext.Ajax.request({
async: false,
url: 'http://127.0.0.1:8081/cors/$catalog/' + className,
success: function(response) {
catalog = Ext.decode(response.responseText);
}
});
return catalog;
}
});
Custom proxy
Ext.define('Wakanda.Proxy', {
extend: 'Ext.data.proxy.Rest',
// alternateClassName: 'SimplyFundraising.data.WakandaProxy',
alias : 'proxy.wakanda',
sortParam: '$orderby',
filterParam: '$filter',
startParam: '$skip',
limitParam: '$top',
// groupersParam: '$group',
reader: 'wakanda',
writer: 'wakanda',
actionMethods: {
create : 'POST',
read : 'GET',
update : 'POST',
destroy: 'POST'
},
buildUrl: function(request) {
debugger;
var modelName = this.model.modelName,
operation = request.operation,
records = operation.records || [],
record = records[0],
id = record ? record.getId() : operation.id,
url = '/cors/' + modelName,
action = request.action;
if (this.appendId && id && (action === 'read' || action === 'destroy')) {
url += '(' + id + ')';
}
request.url = url;
// console.log("buildUrl", this, arguments, request.url);
if (action !== 'read') {
if (action === 'create') action = 'update';
else if (action === 'destroy') action = 'delete';
url = Ext.urlAppend(url, '$method=' + action);
}
if (this.noCache) {
url = Ext.urlAppend(url, Ext.String.format("{0}={1}", this.cacheString, Ext.Date.now()));
}
return url;
},
encodeSorters: function(sorters) {
var min = [],
length = sorters.length,
i = 0, sort = '';
for (; i < length; i++) {
sort += sorters[i].property + ' ' + sorters[i].direction + ' ';
}
return sort;
},
encodeFilters: function(filters) {
var min = [],
length = filters.length,
i = 0, filter = '';
for (; i < length; i++) {
filter += filters[i].property + ' eq ' + filters[i].value + '# ';
}
return filter;
}
});
Custom reader
Ext.define('Wakanda.reader', {
extend: 'Ext.data.reader.Json',
//alternateClassName: 'SimplyFundraising.data.WakandaReader',
alias : 'reader.wakanda',
root: '__ENTITIES',
totalProperty: '__COUNT',
getData: function(data) {
if (Ext.isObject(data) && !data[this.root]) {
data = [data];
}
return data;
}
});
Custom writer
Ext.define('Wakanda.writer', {
extend: 'Ext.data.writer.Json',
// alternateClassName: 'SimplyFundraising.data.WakandaWriter',
alias: 'writer.wakanda',
writeAllFields: false,
getRecordData: function(record) {
var isPhantom = record.phantom === true,
writeAll = this.writeAllFields || isPhantom,
nameProperty = this.nameProperty,
fields = record.fields,
data = {},
changes,
name,
field,
key;
if (writeAll) {
// console.log("getRecordData1", this, arguments);
fields.each(function(field){
if (field.persist) {
name = field[nameProperty] || field.name;
data[name] = record.get(field.name);
} else {
}
});
} else {
changes = record.getChanges();
// console.log("getRecordData2", this, arguments, changes);
for (key in changes) {
if (changes.hasOwnProperty(key)) {
field = fields.get(key);
name = field[nameProperty] || field.name;
data[name] = changes[key];
}
}
if (!isPhantom) {
data[record.idProperty] = record.getId();
data[record.stampProperty] = record.get(record.stampProperty);
}
}
return {'__ENTITIES': [data]};
}
});
Contacts Model
Ext.define('SimplyFundraising.model.Contact', {
extend : 'Wakanda.Model' ,
//constructor: function() {
//alert(“Going to call parent’s overriden constructor…”);
// this.callParent(arguments);
// return this;
// }
});
Contacts Store
Ext.define('SimplyFundraising.store.Contacts', {
extend : 'Ext.data.Store',
model : 'SimplyFundraising.model.Contact',
autoLoad : true,
autoSync : true,
// constructor: function() {
// this.model = Ext.create('SimplyFundraising.model.Contact')
//alert(“Going to call parent’s overriden constructor…”);
// this.callParent(arguments);
return this;
// }
});
Contacts Controller
Ext.define('SimplyFundraising.controller.Contacts', {
extend : 'Ext.app.Controller',
models : ['Contact'],
views : ['contacts.List', 'contacts.Edit'],
init : function() {
this.control({
'contactslist' : {
itemdblclick : this.editContact,
removeitem : this.removeContact
},
'contactslist > toolbar > button[action=create]' : {
click : this.onCreateContact
},
// 'contactsadd button[action=save]': {
// click: this.doCreateContact
// },
'contactsedit button[action=save]' : {
click : this.updateContact
}
});
},
list : function() {
// var mystore = Ext.StoreMgr.lookup('Contacts');
// var myContact = this.getModel('Contact')
// var User = this.getModel('User');
//debugger;
// var mystore = Ext.create('SimplyFundraising.store.Contacts')
// var myContact = this.getModel('Contact').create()
// var bb = myContact.create()
// var rr = Ext.create('SimplyFundraising.model.Contact')
var mystore = Ext.create('SimplyFundraising.store.Contacts')
debugger;
// mystore.proxy.api.read = users.proxy.api.read + '(17)'
//mystore.proxy.extraParams = { $expand: 'ContactType'};
mystore.load();
//var test = Ext.ModelManager.getModel('Contact');
// //var User = this.getContactModel();
// User.load(258, {
// success: function(user) {
// console.log("Loaded user 258: " + user.get('lastName'));
// }
// });
},
editContact : function(grid, record) {
var view = Ext.widget('contactsedit');
view.down('form').loadRecord(record);
this.addnew = false
},
removeContact : function(Contact) {
Ext.Msg.confirm('Remove Contact ' + Contact.data.lastName, 'Are you sure?', function(button) {
if (button == 'yes') {
this.getContactsStore().remove(Contact);
}
}, this);
},
onCreateContact : function() {
var view = Ext.widget('contactsedit');
this.addnew = true
},
// doCreateContact: function (button) {
// var win = button.up('window'),
// form = win.down('form'),
// values = form.getValues(),
// store = this.getContactsStore();
// if (form.getForm().isValid()) {
// store.add(values);
// win.close();
// }
// },
updateContact : function(button) {
var win = button.up('window'), form = win.down('form'), record = form.getRecord(), values = form.getValues(), store = this.getContactsStore();
if (form.getForm().isValid()) {
if (this.addnew == true) {
store.add(values);
} else {
record.set(values);
}
win.close();
}
}
});
I got this working now:
It looks like my custom wakanda model,proxy,reader,writer where not loading. Still a bit confused on how MVC references classes and loads files and instantiates classes, which I asked in other question.
Any way the fix was to add a requires to the custom wakanda model and proxy
For the Wakanda model add requires: ['Wakanda.proxy'],
For Wakanda proxy add requires: ['Wakanda.reader', 'Wakanda.writer'],
now the inheritance is working as expected.

Resources