I'm creating a dynamic controller, according to the new MVC pattern in ExtJS4 and ran into a small problem. I've used the this.control method to attach the controller to my view. When create the controller a second time (going back and forth in my navigation), I have attached them couple times. My question is : What is the best way to destroy a controller or to remove all the listeners that I've setup via the this.control command.
Thanks in advance
Chris
The code of my new controller looks like like :
I create the new controller like this:
var step1Controller = Ext.create("MyApp.controller.Step1Controller", {
application : this.application
});
step1Controller.init();
In in the init function of my controller I've attached my controller to the view like this:
init : function() {
this.addEvents(['step1completed','basecontructionaborted']);
this.setupScreenLayout();
this.getTmpConfiguredControlModelsStore().removeAll();
this.application.fireEvent("addBreadCrumb", "Inbetriebnahme");
this.application.fireEvent("addBreadCrumb", "Schritt 1/3");
this.control({
'#addmodelbutton' : {
click : this.onAddBtnClick
},
'#modelviewer' : {
modelselected : this.onPanelSelect
},
'#navigationcontainer #movemodelleftbutton' : {
click : this.onMoveModelLeftClick
},
'#navigationcontainer #continuestep2' : {
click : this.onContinueStep2Click
},
'#navigationcontainer #abortbutton' : {
click : this.onAbortButtonClick
}
});
console.log('[BaseConstruction | init] completed');
}
Old question, but I killed half a day on solving this, so I'll post how I was able to get around it. This question seems very similar to my own issue. Hope it's useful to someone else.
I am loading controllers/views dynamically, and all listeners were attached via the app.control inside of a controller's init(). Worked fine until I started destroying/initializing views repeatedly. The listeners remained on the views after view.destroy(), so initializing them later down the road caused those listeners (ie render, click, etc) to fire twice.
This solved it for me:
app.control({
'element': {
beforerender: {
fn: function(thing){
// beforerender stuff for thing
thing.on('select', function(this, record, item, index){
console.log('select fired');
});
},
single: true
},
}
});
Note the "single: true" that's attached to the 'beforerender'. That's the crucial part. All other listeners that were previously written like 'beforerender' were moved to inside of it with the .on().
Cheers!
Related
I have two ViewController.
The first one fires an event if I select an item in a treepanel :
// treeController
onItemSelection: function(treeview, record) {
var me = this,
controller = me.getView().getController();
...
controller.fireEvent('myEvent', record);
}
The second one is listening to this event.
The controller is responsible for uploading a file to a specified url.
This url is set by the onMyEvent-function.
// uploadController
...
listen: {
controller: {
'*': {
myEvent: 'onMyEvent'
}
}
},
defaultUrl: 'foo/bar/{id}',
currentUrl: null,
onMyEvent: function(record) {
var me = this;
me.currentUrl = me.defaultUrl.replace('{id}', record.getId());
},
onUploadClick: function (form) {
var me = this;
if (form.isValid()) {
form.submit({
url: me.currentUrl,
...
});
}
},
...
What I want to achieve:
I select an item in the treepanel
-> the event is fired, the onMyEvent-function has been executed.
I click on the button to open the uploadView (the view which is connected to the controller). After that I'll click on the fileupload-button, select a file and click on the uploadbutton.
After the uploadbutton has been pressed, the controller should call the onUploadClick-function and use the previous placed url (currentUrl) for the upload.
The problems I'm facing:
Selecting an item in the treepanel fires the event, but the uploadController is not executing the onMyEvent-function.
When I open the uploadView first and select afterwards a node in the panel, the onMyEvent-function is executed.
When I use the second approach and try to upload the file, I get an error which tells me I haven't specifed the url (its null).
How can I accomplish the process without using the mentioned workaround for 1.?
Thanks in advance.
Your event myEvent is in UploadController. However, controller.fireEvent('myEvent', record); would try to find and fire it in TreeController.
Root cause of this issue is that controller = me.getView().getController(); is going to give you back this/instance of TreeController. When you do me.getView(),it gives you TreeView and me.getView().getController() is going to give you back an instance of TreeController and you need an instance of UploadController cause myEvent is an event of UploadController.
The reason you're able to fire the event when you open UploadView first is cause you're already in UploadController.
Hope that helps!
I'm implementing a simple (at least ,that was the goal) Kendo UI grid that displays two columns: one holding a checkbox, bound to a boolean, and one holding a display name for the item. The checkbox column has a simple template, and the change() event of the checkbox is handled so that the model in the datasource gets updated. I have verified this, and it works.
The data source has been configured for batch, and defines a transport for read and update. Both call a function that perform the ajax call. As I said before, the read function is handled as expected. However, the update function defined on the transport is not. The sync() on the datasource is triggered with a simple button whose click event is hooked to a function that calls datasource.sync() (or grid.saveChanges()).
transport: {
read: function(options) {
return loadStuff(options);
},
update: function (options) {
return updateStuff(options);
}
}
When debugging in the Kendo UI code, it looks like the models attribute on the ModelSet is always empty, and therefore the sync() decides that there's nothing to sync. Anyone got a clue what is happening here?
UPDATE:
Looks like something may be wrong when handling the checkbox check / uncheck. Apparently I should use something like
$('#divGrid').on('click', '.chkbx', function() {
var checked = $(this).is(':checked');
var grid = $('#divGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set("Selected", checked);
});
Unfortunately, it looks like the set() method is not defined on the data item. When debugging, it only contains the data, and no Model object having the set() method.
UPDATE 2:
Tried wrapping the data returned from the ajax call in a model defined with Model.define(). That seems to solve the issue of the model not being dirty, as the _modified property on the model returns true. However, the models array in the ModelSet remains empty. Is this a bug in Kendo UI, or am I going the wrong way?
You don't actually need to bind to click event on the checkboxes.
I´ve posted an example on using it in JSFiddle where you can see it running. This example displays in a grid two columns: first text (tick) and second boolean rendered as a checkbox (selected); the update is batch (so, it's pretty close to what you have).
Questions to keep in mind are:
For displaying the checkbox while not in edit mode, you should define a template, something like this. You might realize that the checkbox is in disabled state by default since you want to edit it as other fields (selecting the cell first). This also guarantees that the model is correctly updated:
{
field : "selected",
title : "Selected",
template: "<input type='checkbox' name='selected' #= selected ? 'checked' : '' # disabled/>"
}
Define in the model that this field is boolean:
schema : {
id : "id",
model: {
fields: {
symbol : { type: "string" },
selected: { type: "boolean" }
}
}
},
Define the transport.update function, something like:
transport: {
read : function (operation) {
// Your function for reading
},
update: function (operation) {
// Display modified data in an alert
alert("update" + JSON.stringify(operation.data.models, null, 4));
// Invoke updating function
// that should ends with an operation.success(the_new_data)
// In this example just say ok
operation.success(operation.data.models)
}
}
EDIT: If you want to be able to modify the checkbox state without having to enter in edit mode first, you should:
Remove the disabled from the template:
{
field : "selected",
title : "Selected",
template : "<input type='checkbox' name='selected' #= selected ? 'checked' : '' #/>"
},
Then bind the click event on checkboxes to the following handler function:
$("#stocks_tbl").on("click", "input:checkbox", function(ev) {
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set("selected", this.checked);
});
Where #stocks_tbl is the id of the div that contains the grid. You might see it running here.
NOTE: It's important the on with the three parameters for making it live
I'm just migrating from Sencha Touch 1.x to Sencha Touch 2 and I can't find a way to pass parameters between views.
Lets say I have to views:
Place (a list with all the places)
PeopleAtPlace (A list of the people for each place)
Now what I need to do is to pass the id of the place that is pressed to the peopleatplace view so it can get the people for that specific view.
I've been reading Sencha's documentation but it's pretty confusing to me.
Could somebody please help me? A code snippet would be great help to me.
Controllers can be the glue between different views. I don't know what kind of views you exactly have, but the following code can serve as a base:
Ext.define('MyApp.controller.TestController', {
extend : 'Ext.app.Controller',
config : {
views : [ // you need to list all views your controller will use
'Place',
'PeopleAtPlace'
],
refs : {
place : 'place', // ComponentQuery used to find the view e.g. xtype, id, etc of the view
peopleAtPlace : 'peopleAtPlace'
},
control : {
place : {
select : 'onPlaceSelected' // use the appropriate event
}
}
},
onPlaceSelected : function (view, record) {
var peopleAtPlaceView = this.getPeopleAtPlace(); // generated by Sencha from the ref property
// now you have the reference to the target view, you can put your logic here
peopleAtPlaceView.doSomething(record);
}
});
Note: I'm a total ignoramus regarding javascript.
I've broken my ExtJS 4.1 MVC app out into several controllers like:
/app/controller/Auth
| |Quiz
| |Result
| |Blah...
|model/...
I want to respond to an "event", not a DOM Event, rather a Ext.form.action.Submit.success event by calling functions in both my Auth and Quiz controllers. The summarized code for the first part is here:
// File: app/controller/Auth.js
attemptLogin : function() {
var form = Ext.ComponentQuery.query('#loginpanel')[0].form;
if (form.isValid()) {
form.submit({
success : function(form, action) {
// THIS IS THE FUNCTION FROM THE CURRENT CONTROLLER
Assessor.controller.Auth.prototype.finishLogin();
// THIS IS THE FUNCTION FROM THE OTHER CONTROLLER
Assessor.controller.Quiz.prototype.setupAssessment();
},
This works but feels wrong. Is there a proper way to do this? It seems like I should fire a unique event that is listened to by both controllers, but I can't understand how to do that with Ext.Event. Any guidance?
Thanks! I'm really grateful for all the great ideas and advice.
It makes sense to me to fire a custom event from the form and simply listen to it in both your controllers, like what you said here:
It seems like I should fire a unique event that is listened to by both
controllers
// File: app/controller/Auth.js
attemptLogin : function() {
var form = Ext.ComponentQuery.down('#loginpanel').form;
if (form.isValid()) {
form.submit({
success : function(form, action) {
// fire the event from the form panel
form.owner.fireEvent('loginsuccess', form.owner);
},
Then in each of your controllers you can listen to it with Controller#control, like this:
Ext.define('YourApp.controller.Auth', {
extend: 'Ext.app.Controller',
init: function() {
var me = this;
me.control({
'#loginpanel': {
loginsuccess: me.someHandler
}
});
},
someHandler: function(form) {
//whatever needs to be done
console.log(form);
}
}
And then add the same thing to your Quiz controller:
Ext.define('YourApp.controller.Quiz', {
extend: 'Ext.app.Controller',
init: function() {
var me = this;
me.control({
'#loginpanel': {
loginsuccess: me.someOtherHandler
}
});
},
someOtherHandler: function(form) {
//whatever needs to be done
console.log(form);
}
}
I've used this approach successfully in 4.1.0 and 4.1.1
It really should be
Assessor.controller.Auth.prototype.finishLogin.apply(this, arguments)
or something along these lines (in order to have a correct this reference that points to the 'owner' of the method, the controller object)
However, why do you use this unorthodox way to call the current controller's method. Just set the scope for the success callback, then call this.finishLogin().
form.submit({
success : function(form, action) {
// THIS IS THE FUNCTION FROM THE CURRENT CONTROLLER
this.finishLogin();
...
},
scope: this
});
Also, you can retrieve another controller instance using Controller#getController.
this.getController('Assessor.controller.quiz').setupAssignment();
Then, if your controller methods are not depending on each other, you could make them both listen to the same event.
Another solution is to fire a custom event once the login is finished. You could do that on the application object
this.application.fireEvent('logincomplete');
and in your controller's init method:
this.application.mon('logincomplete', this.setupAssignment, this);
Please note that you cannot listen to those events via Controller#control - see Alexander Tokarev's blog post for a patch to Ext to achieve this.
There is no standard way to fire events between controllers, but it's possible with some custom hacks. See my recent blog post.
I have also been looking for this and all you need is Asanda.app.getController('quiz').setupAssignment();, where Asanda is the name of your app
You should use a MessageBus if you have to send events between controllers:
Ext.define('MyApp.utils.MessageBus', {
extend : 'Ext.util.Observable'
});
store the message bus in a global var
MsgBus = Ext.create('MyApp.utils.MessageBus');
Where you have to send events:
MsgBus.fireEvent('eventName',eventArg_1,eventArg_2);
Where you have to receive events:
MsgBus.on('eventName', functionHandler,scope); //scope is not mandatory
...
functionHandler:function(eventArg_1,eventArg_2){
...
//do whatever you want
...
}
I'm fiddling with a view and related model that look like that:
App.Views.Addresses = App.Views.Addresses || {};
App.Views.Addresses.Address = Backbone.View.extend({
events: {
"click button#foo" : "clear"
},
initialize: function(model){
this.address = model.model;
this.address.view = this;
_.extend(this, Backbone.Events);
this.render();
},
render: function(){
... rendering stuff
},
clear: function(){
this.address.clear();
}
});
and
var Address = Backbone.Model.extend({
url: function() {
... url stuff
},
clear: function(){
this.destroy();
this.view.remove();
}
});
I'm facing two problems here. The first one:
I have a button with id="foo" in my source and would like the view to catch the 'click' event of this very button and fire the 'clear' event. Problem: This does not work.
Anyway calling 'clear' on my model by hand cleanly removes the data on the server but does not remove the view itself. Thats the second problem. Hopefully someone more experienced can enlighten me.
Thx in advance
Felix
First problem:
Your button must be inside the element rendered by the view.
backbone scope events to inner elements only
You must render your view within this.el element
backbone use that element for delegation
Second problem:
Use events to destroy your view
You should not store the view in the model. This is kind of a "no no" in MVC. Your model already emits a "remove" event when deleted. Your view should listen to it and behave accordingly.
You must remove your view element from the DOM yourself
This is not handled by backbone.
Other general comments:
Views already are extending Backbone.Events
Use this.model instead of this.address