Extjs overrides - loading required file before override - extjs

I am trying to apply a patch using overrides, but I am getting "Uncaught TypeError: Cannot read property 'Table' of undefined " because the Ext.view.Table file has not finished loading by the time the script gets called. How do I make sure the required files gets loaded before this is called?
Ext.define('CSnet.overrides.Table', {
override: 'Ext.view.Table',
getRowStyleTableElOriginal: Ext.view.Table.prototype.getRowStyleTableEl,
getRowStyleTableEl: function() {
var el = this.getRowStyleTableElOriginal.apply(this, arguments);
if (!el) {
el = {
addCls: Ext.emptyFn,
removeCls: Ext.emptyFn,
tagName: {}
}
}
return el;
}
});

You can define a class which handles all your overrides, e.g.
Ext.define('YourApp.Overrider',{
requires: ['TargetClass'],
doOverride: function() {
Ext.define('CSnet.overrides.Table', {
override: 'Ext.view.Table',
// snip
});
}
});
You can requires this class in your app.js and call doOverride in app.launch(), after the framework has been loaded. Additionally, you can require the specific TargetClass that you want to override in the require-config of the Overrider.

Related

Loading HTML templates synchronously

I am trying to render a template a template in Typescript, which is not happening. Here's the code and the browser error:
class QuestionView extends Backbone.View{
template: (data:any) => string;
constructor(options?:any){
var question = this;
require(["text!add-new-question.html"],
function(html) {
question.template = _.template(html);
}
);
_.bindAll(this, "render");
}
render(){
var data = this.model.toJSON();
var html = this.template(data);
return this;
}
}
Error:
Uncaught TypeError: Object #<QuestionView> has no method 'template' Main.ts:49
QuestionView.render Main.ts:49
(anonymous function) Main.ts:57
Update:
As pointed out below, this is happening because of the require functions returns after the the render is finished its execution. I've trying running with a setInterval() and it works. How can I make the require function a synchronous one?
You should try using jquery-ajax insted of require.js
var ajxParam: JQueryAjaxSettings = {
async: false, timeout: 200000,
url: "http://somthing", dataType: "html",
cache: false,
success: (htmltext: any, textStatus: string, jqXHR: JQueryXHR) => {
},
error: (jqXHR: JQueryXHR, textStatus: string, errorThrow: string) => {
// show error?
}
}
$.ajax(ajxParam);
//you can bind your data here

How to dynamically update a Marionette CollectionView when the underlying model changes

Seems like this should be obvious, but there seem to be so many different examples out there, most of which cause errors for me, making me think they are out of date. The basic situation is that I have a MessageModel linked to a MessageView which extends ItemView, MessageCollection linked to a MessageCollectionView (itemView: MessageView). I have a slightly unusual scenario in that the MessageCollection is populated asynchronously, so when the page first renders, it is empty and a "Loading" icon would be displayed. Maybe I have things structured incorrectly (see here for the history), but right now, I've encapsulated the code that makes the initial request to the server and receives the initial list of messages in the MessageCollection object such that it updates itself. However, I'm not clear, given this, how to trigger displaying the view. Obviously, the model shouldn't tell the view to render, but none of my attempts to instantiate a view and have it listen for modelChange events and call "render" have worked.
I have tried:
No loading element, just display the CollectionView with no elements on load, but then it doesn't refresh after the underlying Collection is refreshed.
Adding modelEvents { 'change': 'render' } to the view --> Uncaught TypeError: Object function () { return parent.apply(this, arguments); } has no method 'on'
I also tried this.bindTo(this.collection..) but "this" did not nave a bindTo method
Finally, I tried, in the view.initialize: _.bindAll(this); this.model.on('change': this.render); --> Uncaught TypeError: Object function () { [native code] } has no method 'on'
Here is the code
Entities.MessageCollection = Backbone.Collection.extend({
defaults: {
questionId: null
},
model: Entities.Message,
initialize: function (models, options) {
options || (options = {});
if (options.title) {
this.title = options.title;
}
if (options.id) {
this.questionId = options.id;
}
},
subscribe: function () {
var self = this; //needed for proper scope
QaApp.Lightstreamer.Do('subscribeUpdate', {
adapterName: 'QaAdapter',
parameterValue: this.questionId,
otherStuff: 'otherstuff',
onUpdate: function (data, options) {
console.log("calling sync");
var obj = JSON.parse(data.jsonString);
self.set(obj.Messages, options);
self.trigger('sync', self, obj.Messages, options);
}
});
},
});
Views.MessageCollectionView = Backbone.Marionette.CollectionView.extend({
itemView: Views.MessageView,
tagName: 'ul',
// modelEvents: {
// 'change': 'render'
// },
onAfterItemAdded: function (itemView) {
this.$el.append(itemView.el);
}
});
var Api = {
subscribe: function (id) {
var question = new QaApp.Entities.Question(null, { id: id });
question.subscribe();
var questionView = new QaApp.Views.QuestionView(question);
QaApp.page.show(questionView);
}
};
I am very grateful for all the help I've received already and thanks in advance for looking.
Try this:
var questionView = new QaApp.Views.QuestionView({
collection: question
});

backbone extension file loads, some helpers work, one doesn't

I have a backbone-extend.js file that I load in the require define in app.js. It has a Backbone.View extender class defining a couple helper methods. Two of the methods work just fine in my views, one always errors with Uncaught TypeError: Object [object global] has no method 'gotoUrl'. Why would just this one method be not defined but the other two are working fine? Do you see any issue in this code...
// Filename: backbone-extend.js
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone) {
var helpers = {
eventSyncError: function(model,response,options) {
console.log('Sync error='+response.statusText);
$('#server-message').css({'color':'red', 'font-weight':'bold'}).text(response.statusText);
},
gotoUrl: function(url,delay) {
var to = setTimeout(function() { Backbone.history.navigate(url, true); }, delay);
},
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i) {
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
}
_.extend(Backbone.View.prototype, helpers);
});
Here is the code in view that calls it...
eventSyncMemberSaved: function(model,response,options) {
console.log("Member saved!");
$('#server-message').css({'color':'green', 'font-weight':'bold'}).text("Member saved!");
this.gotoUrl('members',2000);
//setTimeout(function() { Backbone.history.navigate('members', true); }, 2000);
},
saveMember: function() {
var data = this.getFormData($('#member-form'));
this.member.save(data, { success: this.eventSyncMemberSaved });
},
Thanks in advance for your help. I'm stuck.
The context of this is different in the success callback.
It no longer points to the view as it points to the xhr object
So it throws an error as that method is not available on the xhr object
To resolve it you need to bind the context of this to the success handler so that it points to the right object.
So in the initialize of the view add this code
initialize: function() {
_.bindAll(this, 'eventSyncMemberSaved');
}

Backbone Model gives this.set not a function in Model.initialize

I've a model listen on the vent for a event update:TotalCost, which is triggered from (unrelated) Collection C when any model M belonging to collection C changes.
This event is coded in the initialize method as below. On receiving the event I get the following error:
TypeError: this.set is not a function
this.set({ "totalsale": value});
CostModel = Backbone.Model.extend({
defaults: {
totalSale: 0,
totalTax: 0
},
initialize: function(attrs, options) {
if(options) {
if(options.vent) {
this.vent = options.vent;
}
}
this.vent.on("update:TotalCost", function(value) {
this.set({ "totalSale": value}); **//ERROR HERE**
});
}
});
It is highly possible you've forgot to add the new keyword before your model for example you have:
var user = UserModel();
// instead of
var user = new UserModel();
Have you tried using a closure?
CostModel = Backbone.Model.extend({
defaults: {
totalSale: 0,
totalTax: 0
},
initialize: function(attrs, options) {
var self = this;
if(options) {
if(options.vent) {
this.vent = options.vent;
}
}
this.vent.on("update:TotalCost", function(value) {
self.set({ "totalSale": value});
});
}
});
Perhaps you want this to refer to current CostModel instance, to do so you need to pass this to this.vent.on call so event callback will be executed in context of model:
this.vent.on("update:TotalCost", function(value) {
this.set({ "totalSale": value});
}, this);
it may be due to 'set' works on model not on object. so you can, first convert your object in to model then try..
in example:
new Backbone.Model(your_object).set('val', var);
Another cause of this error can be if you try to create a new model without using the "new" keyword
I was getting this mysterious error when using it with Parse. I had:
Parse.User().current().escape("facebookID")
... when I should have had:
Parse.User.current().escape("facebookID")
Removed the extra () and it works fine now.
Another cause:
// render() method in view object
setInterval(this.model.showName, 3000);
// showName() method in model object
showName: function(){
console.log(this.get('name')); // this.get is not a function
}

Reusable Action in Ext JS MVC

I have a Grid Panel with a toolbar and an context menu.
The toolbar has a edit button and the context menu has a edit menu item.
Both shares the same properties (text, icon and handler)
Ext has something called Action which makes it possible to share functionality etc. between components, but til now I have had no success getting it to work in the MVC architecture
(I am using the new MVC architecture in 4.0)
My Action class looks like this:
Ext.define( 'App.action.EditAction', {
extend: 'Ext.Action',
text: 'Edit',
handler: function()
{
Ext.Msg.alert('Click', 'You did something.');
},
iconCls: 'icon-edit-user' ,
});
And in my context menu
requires: ['App.action.EditAction'],
initComponent: function()
{
var editUser = new App.action.EditAction();
this.items = [
editUser,
{
// More menuitems
}
...
];
this.callParent(arguments);
When running the code I get "config is undefined" in the console.
Can anyone point out what I am doing wrong?
Thanks in advance,
t
Passing an empty config to your constructor will avoid the error, but have unwanted consequences later because, unfortunately, the base class (Ext.Action) relies on this.initialConfig later on. For example, if you called editUser.getText() it would return undefined instead of the expected 'Edit'.
Another approach is to override your constructor to allow a no-arg invocation and apply your overridden configuration:
Ext.define( 'App.action.EditAction', {
extend: 'Ext.Action',
text: 'Edit',
constructor: function(config)
{
config = Ext.applyIf(config || {}, this);
this.callParent([config]);
},
handler: function()
{
Ext.Msg.alert('Click', 'You did something.');
},
iconCls: 'icon-edit-user' ,
});
As per Ext.Action constructor
constructor : function(config){
this.initialConfig = config;
this.itemId = config.itemId = (config.itemId || config.id || Ext.id());
this.items = [];
}
You must supply config not to get config is undefined exception in the second line (precisely in config.itemId part).
Updating your code as var editUser = new App.action.EditAction({}); should help(passing new empty object as config).
Surely, you could add some properties to the config object too.

Resources