backbone.js: encapsulating view functions? - backbone.js

Pretty new to backbone.js so forgive me of my ignorance. I'm wondering, is there a way to encapsulate functions within the View class specifically?
I ask because when setting default events...
events {
'click .something' : 'doSomething'
}
... I'd prefer to have doSomething be nested in an encapsulating object for optimal organization. For example:
ui: {
doSomething: function() {}
}
But then I can't seem to get the default events to work.
events {
'click .something' : 'ui.doSomething' // this doesn't work
}
Any help is greatly appreciated. Or, if you can tell me why I shouldn't be doing this then I'd appreciate that, as well. Thanks!

Looking through the source that binds the events (delegateEvents) which is called from the constructor, it is pretty clear that it works on variables with in the scope of the object.
http://documentcloud.github.com/backbone/docs/backbone.html#section-118
You could, however, override delegateEvents to be a bit smarter... You could parse the value for dots and chain your tokens. You could even check the type of the value and use an actual function in place of the string. That might give you better control the way you want.
More info on the delegateEvents function: http://documentcloud.github.com/backbone/#View-delegateEvents

Related

Backbone JS - event problems adding multiple Views into same parent container

My code fetches a Collection from the server and iterates through it. For each model fetched it creates a View that is appended to the same parent element. Each of these views has a "click" event that triggers a function.
The problem is that clicking on any item in the list causes the event function to trigger for ALL elements in the list. The only workaround I have is to make the function itself dynamic and try to determine if it should run based on things like the ID of the item clicked:
'click .request_box': function(e) {
var myid = $(e.currentTarget).attr("id");
// code here which determines whether the function runs
}
}
This is a workaround, but it is also a hack, and I'm sure there has to be a better way of dealing with what must be a common problem (creating a list). Repeat searching around the web does not suggest any better way, so I am posting in the hope someone with more experience using Backbone can offer suggestions on a better way to approach this problem....
Thank you in advance.

UI hash problems with Backbone Marionette Layout

In the following Layout, I am adding a CollectionView to display a SELECT list within onRender. Immediately after that, I am using the ui hash to enable or disable all controls within the view. This does not work for the SELECT generated by new App.View.Categories.
Should it? Or does the UI hash not work on Regions within a Layout?
App.View.UploadFile = Backbone.Marionette.Layout.extend({
template: '#upload-file-template',
regions:{
category: 'td:nth-child(4)'
},
ui:{
inputs: 'textarea, select, .save'
},
onRender: function(){
this.category.show(
new App.View.Categories({
collection: App.collection.categories
}) // generates the SELECT list
);
console.log(this.ui.inputs); // Length 2. Missing select.
console.log(this.$('textarea, select, .save')); // Length 3
this.ui.inputs.prop(
'disabled', (this.model.get('upload_status')!='staged')
);
}
});
This should be working the way you expect it to work. The code in question in the Marionette source is here: https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.itemview.js#L49-L51
The call to bindUIElements() is what converts the ui hash in to jQuery selector objects, and it is called right before the onRender method is called.
Are you seeing errors? Or is the selector simply returning nothing, and having no affect on the elements?
Update:
Ah! Of course... I wasn't paying attention to your code close enough. You're correct in that the UI element selectors happen before you're adding the the sub-view to the region. I've never run in to this situation before... but this seems like something we would want to fix / support.
For now, the best workaround I can suggest would be to call 'this.bindUIElements();' at the very end of your onRender method. This would force the ui elements to re-bind to the selectors.
I'll also add an issue to the github issues list, to look in to a better solution for this. i don't know when i'll be able to get to this, but this will at least get it on the list of things to fix.

Best practice for overriding classes / properties in ExtJS?

I have an Ext.form.field.Text and I want to override the setValue function.
What is the recommended way to override this class functionality in ExtJS? Ext.override?
For clarification:
By real class modification I mean a intended permanent
modification/extension of a class, which should always be done by extending a class.
But it is not a temporary solution for just a specific problem (bug-fix, etc.).
You have at least four options how to override members of (Ext) Classes
prototype I guess is well known and allows you to override a member for all instances of a class. You can use it like
Ext.view.View.prototype.emptyText = "";
While you can't use it like
// callParent is NOT allowed for prototype
Ext.form.field.Text.prototype.setValue = function(val) {
var me = this,
inputEl = me.inputEl;
if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
inputEl.removeCls(me.emptyCls);
me.valueContainsPlaceholder = false;
}
me.callParent(arguments);
me.applyEmptyText();
return me;
};
Here's a JSFiddle
This variant should not be used for real class modifications.
Ext.override does nearly the same then prototype but it fully applies to the ExtJS Class-system which allows you to use callParent()
You can use it like
// callParent is allowed for override
Ext.override('Ext.form.field.Text', {
setValue: function(val) {
this.callParent(['In override']);
return this;
}
});
Here's a JSFiddle (c-p error fixed! Thanks to #nogridbag)
Use case: I faced a (I think still existing) bad behavior of a
radiogroup where ExtJS expect a object (key-value-pair) for correct
setting of the value. But I have just one integer on my backend. I
first applied a fix using Ext.override for the setValue()
method and afterwards extend from radiogroup. There I just make a
Key-Value-Pair from the given value and call the parent method with
that.
As #rixo mentioned this can be used for overriding a instance member. And may therefore be qualified for overriding even mixins (I never tested it myself)
var panel = new Ext.Panel({ ... });
Ext.override(panel, {
initComponent: function () {
// extra processing...
this.callParent();
}
});
This variant should not be used for real class modifications.
Extending a existent class to apply additional behavior & rendering. Use this variant to create a subtype that behaves different without loosing the original type.
In the following example we extend the textfield with a method to change the labelcolor when setting a new value called setColored and override the setValue method to take care of removing a label color when setValue is called directly
Ext.define('Ext.ux.field.Text',{
extend: 'Ext.form.field.Text',
widget: 'uxtextfield',
setColored: function(val,color) {
var me = this;
if (me.settedCls) {
me.removeCls(me.settedCls);
}
me.addCls(color);
me.settedCls = color;
me.setValue(val,true);
},
setValue: function(val,take) {
var me = this;
if (!take && me.settedCls) {
me.removeCls(me.settedCls);
}
me.callParent(arguments);
return me;
}
});
Here's a JSFiddle
Overriding per instance will happen in really rare cases and might not be applicable to all properties. In such a case (where I don't have a example at hand) you have a single need for a different behavior and you might consider overriding a setting just per instance. Basically you do such things all times when you apply a config on class creation but most time you just override default values of config properties but you are also able to override properties that references functions. This completely override the implementation and you might allows don't have access to the basetype (if any exist) meaning you cannot use callParent. You might try it with setValue to see that it cannot be applied to a existing chain. But again, you might face some rare cases where this is useful, even when it is just while development and get reimplemented for productive. For such a case you should apply the override after you created the specific by using Ext.override as mentioned above.
Important: You don't have access to the class-instance by calling this if you don't use Ext.override!
If I missed something or something is (no longer) correct, please comment or feel free to edit.
As commented by #Eric
None of these methods allow you to override mixins (such as Ext.form.field.Field). Since mixin functions are copied into classes at the time you define the class, you have to apply your overrides to the target classes directly
The answer by #sra is great and was very helpful to me in gaining a deeper understanding of the override functionality available in Ext, but it does not include the way that I most commonly implement overrides which looks something like this:
Ext.define('my.application.form.field.Text' {
override: 'Ext.form.field.Text'
getValue: function () {
// your custom functionality here
arguments[1] = false;
// callParent can be used if desired, or the method can be
// re-written without reference to the original
this.callParent(arguments)
}
});
I'm still using Ext 5 so I would then load this file in my Application.js and add it to the requires array there which applies the override to the app globally. I think Ext 6 projects include an override folder and simply adding this file to that folder ensures the override is applied.
This is the only way that works for me in ExtJS 7.
Example:
app/desktop/overrides/Toast.js
Ext.define(null, {
override: 'Ext.window.Toast',
show : function () {
this.callParent();
// Your custom code here...
}
});

Test Driving Backbone view events

I am trying to test drive a view event using Jasmine and the problem is probably best explained via code.
The view looks like:
App.testView = Backbone.View.extend({
events: { 'click .overlay': 'myEvent' },
myEvent: function(e) {
console.log('hello world')
}
The test looks something like:
describe('myEvent', function() {
it('should do something', function() {
var view = new App.testView();
view.myEvent();
// assertion will follow
});
});
The problem is that the view.myEvent method is never called (nothing logs to the console). I was trying to avoid triggering from the DOM. Has anyone had similar problems?
(Like I commented in the question, your code looks fine and should work. Your problem is not in the code you posted. If you can expand your code samples and give more info, we can take another look at it. What follows is more general advice on testing Backbone views.)
Calling the event handler function like you do is a legitimate testing strategy, but it has a couple of shortcomings.
It doesn't test that the events are wired up correctly. What you're testing is that the callback does what it's supposed to, but it doesn't test that the action is actually triggered when your user interacts with the page.
If your event handler needs to reference the event argument or the test will not work.
I prefer to test my views all the way from the event:
var view = new View().render();
view.$('.overlay').click();
expect(...).toEqual(...);
Like you said, it's generally not advisable to manipulate DOM in your tests, so this way of testing views requires that view.render does not attach anything to the DOM.
The best way to achieve this is leave the DOM manipulation to the code that's responsible for initializing the view. If you don't set an el property to the view (either in the View.extend definition or in the view constructor), Backbone will create a new, detached DOM node as view.el. This element works just like an attached node - you can manipulate its contents and trigger events on it.
So instead of...
View.extend({el: '#container'});
...or...
new View({el:'#container'});
...you should initialize your views as follows:
var view = new View();
$("#container").html(view.render().el);
Defining your views like this has multiple benefits:
Enables testing views fully without attaching them to DOM.
The views become reusable, you can create multiple instances and render them to different elements.
If your render method does some complicated DOM manipulation, it's faster to perform it on an detached node.
From a responsibility point of view you could argue that a view shouldn't know where it's placed, in the same way a model should not know what collection it should be added to. This enforces better design of view composition.
IMHO, this view rendering pattern is a general best practice, not just a testing-related special case.

Backbone boilerplate Events

What is the best way to bind events to a Backbone boilerplate application? I've been trying to bind my events directly to the models associated with my views, in my views, but it doesn't seem to be working. I see within 'namespace.js', that there is an app key that extends Backbone.Events like so:
// Keep active application instances namespaced under an app object.
app: _.extend({}, Backbone.Events)
I don't fully understand how to use it...
I was able to get things working without the boilerplate, but it does provide some very cool functionality, so I'd love to be able to use it. Thanks!
ADDED
the code I was using was with the underscore bind method like so:
this.module.bind('change', this.render);
But then, I realized that 'this.model' is returning undefined, and so this doesn't work. I really am not sure how the boilerplate wants me to reference my model from the view.
I'm not sure if it is a typo that you copied from your code or a typo you only entered here, but I believe this.module (which IS undefined) should be this.model, which you also must be sure to pass in when you instantiate your view, of course, as so:
myView = new BBView({model: myModel});
then you can say this.model.bind('change', this.render); or this.model.on('change', this.render); for the most recent version of Backbone
I frequently bind my views to change events on my models in this way.
As for extending Backbone.Events, the way I have used it is to create an independent "event aggregator" that will help connect events between different views on your page. Let's say for example you have some action on one view that needs to set off an action on another view. In this case, you can pass your event aggregator object as an option to each of your views when you instantiate them, so that they can both trigger events or bind to events on a common object (i.e. your event aggregator).
whatsUp = _.extend({}, Backbone.Events) // the aggregator
myFirstView = new FirstBBView ({whatsUp: whatsUp});
(the aggregator shows up as this.options.whatsUp inside the view)
mySecondView = new SecondBBView2 ({whatsUp: whatsUp});
inside FirstBBView:
this.options.whatsUp.bind('specialEvent', function(arg1,arg2) {
// do stuff
});
inside SecondBBView, when something important happens:
this.options.whatsUp.trigger('specialEvent', {arg1: 'some data', arg2: 'more data'});
For a great explanation, see this great article by Derick Bailey

Resources