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
...
}
Related
I would like to turn a primitive event (a click) into a semantic event, like "deleteTodo"
This is described here, but not how to implement :(
I have the following code:
App.TodoView = Em.View.extend({
click: function(e) {
this.trigger("deleteTodo");
}
});
App.Router.map(function(match) {
match('/').to('index');
});
App.IndexRoute = Ember.Route.extend({
deleteTodo: function(e) {
// this code is never executed :(
}
}) ;
After I perform the 'click', I see that the TodoView click function is called, but not the deleteTodo function from the IndexRoute. Any suggestions what might go wrong here ?
CHeers
You can use this.get("controller").send("deleteTodo"). This will send a message to the controller, if the controller doesn't handle deleteTodo it will bubble to the router and be handled there.
click: function(e) {
this.get('controller').send("deleteTodo");
}
In your router you will also need to define the event:
events: {
doStuff: function(e) {
alert("Do stuff") ;
}
}
http://jsfiddle.net/9Xasr/7/
I would typically do record deletion in the controller. Seems like putting that in a router event would not be ideal.
There's a addPost function in my router. I don't want to re-create the postAddView every time the function is invoked:
addPost: function () {
var that = this;
if (!this.postAddView) {
this.postAddView = new PostAddView({
model: new Post()
});
this.postAddView.on('back', function () {
that.navigate('#/post/list', { trigger: true });
});
}
this.elms['page-content'].html(this.postAddView.render().el);
}
Here's the PostAddView:
PostAddView = backbone.View.extend({
events: {
'click #post-add-back': 'back'
}
, back: function (e) {
e.preventDefault();
this.trigger('back');
}
});
The first time the postAddView is rendered, the event trigger works well. However, after rendering other views to page-content and render postAddView back, the event trigger won't be trigger anymore. The following version of addPost works well, though.
addPost: function () {
var that = this, view;
view = new PostAddView({
model: new Post()
});
this.elms['page-content'].html(view.render().el);
view.on('back', function () {
delete view;
that.navigate('#/post/list', { trigger: true });
});
}
Somewhere you are calling jQuery's remove and that
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
so the delegate call that Backbone uses to bind events to your postAddView.el will be lost. Then, when you re-add your postAddView.el, there are is no delegate attached anymore and no events are triggered. Note that Backbone.View's standard remove method calls jQuery's remove; a few other things in jQuery, just as empty will do similar things to event handlers. So the actual function call that is killing your delegate could be hidden deep inside something else.
You could try calling delegateEvents manually:
this.elms['page-content'].html(this.postAddView.render().el);
this.postAddView.delegateEvents();
or better, just throw the view away and create a new one every time you need it. Your view objects should be pretty light weight so creating new ones should be cheap and a lot less hassle than trying to keep track of the existing views by hand.
If you really want to reuse the current DOM and View you do not need to set again and again the element as you are doing, everything that you call .html() you are destroying the DOM of the View and generating again and losing events. Also I prefer always to add the "el" in the DOM before render the View. I will have your function in this way:
addPost: function () {
if (!this.postAddView) {
this.postAddView = new PostAddView({
model: new Post()
});
this.postAddView.on('back', this.onBack);
this.elms['page-content'].html(this.postAddView.el);
}
this.postAddView.render();
},
onBack : function () {
this.navigate('#/post/list', { trigger: true });
}
I'm not fan of the use of local variables to refer to "this". If all of your Views uses _.bindAll(this) in the initialize method you could bind your events to your view and could use this(check how I transformed onBack).
With my code there is not a need to manually call this.delegateEvents()
Noob question here:
I'm using ASP.NET MVC 3 and I'm trying to save an entity through Backbone. Here's what I have:
I defined my Backbone model (Program) as such:
var Program = Backbone.Model.extend({
defaults: function () {
return { name: "" };
},
initialize: function (attrs) {
this.set('name', attrs.name);
},
urlRoot: '/program/add'
});
Then I hook up the model save on the click event of a button:
$('.add-program').click(function () {
var programName = $('.program-name').val();
var program = new Program({ name: programName });
program.save(null, {
success: function (model, response) {
alert('success');
},
error: function (model, response) {
alert('error');
}
});
});
It works on IE (surprisingly!) - ProgramController.Add(string name) gets called fine and I get a success response. But I'm having issues on Chrome and FF - They both trigger the error callback with the slight difference that on Chrome my Controller Action doesn't even get hit at all (it does on FF though). The funny thing is that my action breakpoint does get hit on FF, with the appropriate param value, but still get the error callback.
I'm not sure what's going on here. I tried debugging through Firebug/Chromebug and don't see much on the error callback params (the errorStatus is just ... well... "error"!). I also tried looking at the Network tab and Fiddler and I don't see anything that rings a bell (maybe I'm not looking at the right place). I also tried doing a straight jquery ajax call to the controller and still get the same weird behavior.
Just in case, here's the MVC action (although I don't think the issue is here):
[HttpPost]
public JsonResult Add(string name)
{
var stubbedResponse = new {id = Guid.NewGuid()};
return Json(stubbedResponse);
}
Any ideas what could be causing this?
A Fiddle http://jsfiddle.net/Uj5Ae/2 with your client code seems to be OK. Something with your server response? Or Backbone and Underscore versions not matching?
Or maybe the return false at the end of the click handler, if the event propagation is not handled elsewhere.
Spoiler : that was the event propagation :)
I am creating a webapp where user creates an inventory of items and he uses folders to categorize them. Now suppose I have two folders like this:
All items (route: /)
Closet items (route: #get/closet/id)
When I navigate between these routes, I want to dispose of the models rendered in the previous route. How and where should I do that? Is there an event which is triggered when I navigate to a new route where may be I can perform this operation?
There are lots of ways to approach this, and it really depends on how you're doing the navigation. If you're changing routes with actual links, or by using router.navigate(), your router will dispatch a route:<route name> event that you can listen to, passing the same arguments to the handler as it passes to the route function.
In what turned out to be a demonstration of just how long it takes to set up test case code with Backbone, I made you a jsFiddle to illustrate this approach: http://jsfiddle.net/nrabinowitz/ZrgJF/7/
A lot of this is just setup code; the important parts for this question are the router:
var MyRouter = Backbone.Router.extend({
routes: {
'view/:id' : 'openView'
},
openView: function(id) {
app.openView(id)
}
});
router = new MyRouter();
And the view, which binds removal to the route:
var MyView = Backbone.View.extend({
initialize: function(opts) {
this.id = opts.id;
router.bind('route:openView', this.dispose, this);
},
// id is the same as the route argument
dispose: function(id) {
if (id != this.id) {
this.remove();
}
}
// etc
});
I have a multiple files uploadify setting with:
'onComplete' : function(event, ID, fileObj, response, data) {
myCollection.add({params parsed from response json});
}
which triggers (trough this.collection.bind('add', this.add)) this collection view method:
add: function(obj) {
var view = new MyModelView({model: obj});
this.$('.insert-models-here').append(view.render().el);
return this;
},
The new MyModelView call triggers: MyModelView::initialize() which is here:
initialize: function() {
var t = $('#photo-template').html();
this.template = _.template(t);
this.model.view = this;
},
And every _.template() calls jumps inside __flash__toXML() method from which all thread is stopped.
The result is no model added inside my collection from any uploadify event.
Does anyone knows why and how to avoid this?
Ok, I found solution.
Problem was in using underscore in uploadify events so I replace underscore _.templates with icanhaz and rewrite my add() collection view method this way to workaround any underscore functionality:
add: function(obj) {
var view = new MyModelView({model: obj});
$('.insert-models-here').first().append(view.render().el);
return this;
},
Hope someone will call my name in future..