Access static members in mixins - static-methods

The instruction this.constructor doesn't work in mixins. I get an undefined value. I wonder why it happens and is it possible to use this instruction. There is a code example:
qx.Mixin.define("MZoomable", {
statics: {
MAX_ZOOM: 500
},
members: {
printMaxZoom: function(){
alert(this.constructor.MAX_ZOOM);
}
}
});
qx.Class.define("MyClass", {
extend: qx.core.Object,
include: [MZoomable],
constuct: function(){
this.base(arguments);
}
});
const o = new MyClass();
o.printMaxZoom();
alert in printMaxZoom will show undefined word.

The answer is that this.constructor refers to the class of the object at runtime, and that would be MyClass. I would expect that if you modified printMaxZoom to be:
printMaxZoom: function(){
alert(this.constructor === MyClass);
}
Then you would get an alert that says "true".
This is an inherent characteristic an environment where the type is determined (including the addition of a mixin) at runtime.
If you want to refer to static members of a Mixin, you should use the absolute syntax, eg:
printMaxZoom: function(){
alert(MZoomable.MAX_ZOOM);
}
Note that it is always good practice to use the absolute path for static variables, and it is often a bug to use this.constructor as a shortcut.
For example:
qx.Class.define("MyClassOne", {
extend: qx.core.Object,
construct: function(){
this.base(arguments);
alert(this.constructor.MY_VALUE);
},
statics: {
MY_VALUE: 23
}
});
qx.Class.define("MyClassTwo", {
extend: MyClassOne
});
// creates an alert that says "23"
var one = new MyClassOne();
// creates an alert that says "undefined"
var one = new MyClassTwo();
The issue is the same as the one in your question, in that this.constructor is the actual class of the object, and not the class (or mixin) where the this.constructor statement appears.

Related

why behaviors are not allowed to pass dynamically?

I am working on Marionette.behavior.I was trying to pass the behaviors hash dynamically at the time of view initialization but it is not getting assigned to the behaviors object of view.because behaviors are getting initialized at the time of view construction.
so we achieved the solution in the following way but is it the right way to achieve it?
is there any other way to achieve? and
why behaviors are not allowed to pass dynamically?
Here's the code:
var Behaviour = new Marionette.Application();
Behaviour.addRegions({
mainRegion:"#main-region"
});
var Person = Backbone.Model.extend({
defaults:{
firstName:"NA",
lastName:"NA",
phoneNumber:"NA",
presentAddr:"NA",
permanantAddr:"NA"
}
});
var buttonView=Marionette.ItemView.extend({
template:"#buttontemplate",
constructor:function(options){
this.behaviors = options.behaviors;
Marionette.ItemView.apply(this, arguments);
},
events:{
"click .display":"displayDetail"
},
displayDetail:function(){
this.triggerMethod("DisplayPersonDetails");
},
//behaviors:{Behavior1:{ },Behavior2:{ }}
})
var PersonDetailsView = Marionette.ItemView.extend({
template:"#static-template",
ui: {
"Change": ".change"
},
events:{
"click #ui.Change":"changeBehavior"
},
changeBehavior:function(){
},
});
var Behavior1 = Marionette.Behavior.extend({
onDisplayPersonDetails:function(){
var person=new Person({firstName:"abhijeet",lastName:"avhad",phoneNumber:"9604074690",permanantAddr:"sangamner",presentAddr:""})
var myView = new PersonDetailsView({model:person});
Behaviour.mainRegion.show(myView);
}
});
var Behavior2 = Marionette.Behavior.extend({
onDisplayPersonDetails:function(){
var person =new Person({firstName:"abhijeet",lastName:"avhad",phoneNumber:"9604074690",permanantAddr:"",presentAddr:"shivajinagar"})
var myView =new PersonDetailsView({model:person});
Behaviour.mainRegion.show(myView);
}
});
Behaviour.on("initialize:after", function(){
console.log(" started!");
Marionette.Behaviors.behaviorsLookup = function() {
return window.Behaviors;
};
window.Behaviors = {};
window.Behaviors.Behavior1 = Behavior1;
window.Behaviors.Behavior2 = Behavior2;
var buttonview=new buttonView({behaviors:{Behavior1:{ },Behavior2:{}}});
Behaviour.mainRegion.show(buttonview);
});
Behaviour.start();
The other way of achieving that is in your definition declare a function that returns the behaviors supplied at initialization, like this:
var buttonView=Marionette.ItemView.extend({
...
behaviors: function () {
return this.options.behaviors;
},
...
This is because the Marionette applies the behaviors in the constructor:
if (_.isObject(this.behaviors)) {
new Marionette.Behaviors(this);
}
You may try to do the same in your initialize method, but I'm not sure if it will work correctly if you already had some behaviors assigned beforehand.
After hacking through the source, I've come up with the following. It breaks encapsulation, which leads me to believe that there is probably a better way. Nonetheless, until I find it, this is going straight into production.
// Define Behavior.
var Behavior1 = { /* Behavior definition */ }
// Create View like normal.
var view = new ItemView({
behaviors: {
behavior1: { behaviorClass: Behavior1 }
}
});
// Here's the ugly part.
view.undelegateEvents();
view._behaviors = Marionette.Behaviors(subview);
view.delegateEvents();
After you do that, your Behaviors should all work.
Behavior can be passed directly with behaviorClass property within declaration of behaviors:
As seen in the marionette.behaviors docs, for example we have Tooltip behavior, which we want to pass directly and not from global list.
define(['marionette', 'lib/tooltip'], function(Marionette, Tooltip) {
var View = Marionette.ItemView.extend({
behaviors: {
Tooltip: {
behaviorClass: Tooltip, // <-- passing the behavior directly here
message: "hello world"
}
}
});
});

How to discard/reject an extra attribute in Backbone Model initialize()

I have a problem while initializing a Backbone model with some data coming from Jackson.
The received data happens to have a listPropertyValue, which is originally a Java List of objects. When doing the initialize() method I make it a Backbone collection without much problem.
But the final SomeModel constructor also adds an attribute called listPropertyValue as a JavaScript array, which I don't want.
How may I discard or reject this array and which is the right way to do it?
Here is my code:
var SomeModel = Backbone.Model.extend({
defaults : {
id:null,
name:'',
order:null,
isRequired:null,
}
initialize : function(options) {
if(options.listPropertyValue !== undefined) {
this.set('collectionPropertyValue', new PropertyValueCollection(options.listPropertyValue))
}
// I thought of doing this. Don't know if it's the right thing to do
// this.unset('listPropertyValue', { silent: true });
}
My concern is not only how to do it, but how to do it in a proper Backbone way.
(I assume you're getting this data from an API somewhere.)
You should define a parse method in your model to return only the data you're interested in:
parse: function(response){
return _.omit(response, "listPropertyValue");
}
Backbone will do the rest for you: every time it receives API from the data it will call parse automatically.
For more info: http://backbonejs.org/#Model-parse
I finally did it. I used the same code I published but it didn't work until I used backbone with version 1.1.2 (I was using 1.0.0 or similar).
var SomeModel = Backbone.Model.extend({
defaults : {
id:null,
name:'',
order:null,
isRequired:null,
}
initialize : function(options) {
if(options.listPropertyValue !== undefined) {
this.set('collectionPropertyValue', new PropertyValueCollection(options.listPropertyValue));
}
this.unset('listPropertyValue', {
silent : true
});
}
}

Passing JSON object as parameter from View to Controller function?

Basically I've a panel called DummyPanel, Now on dummypanel initialize event I've called a controller function like as follows:
var me = component;
var fieldCollection =
{
"Order" : 'ordNumber',
"Ref": 'refNumber'
};
me.fireEvent('myControllerFunction','Param1', fieldCollection, 'Param3');
Now I want to get fieldCollection JSON object value within function myControllerFunction, to get value from fieldCollection I'm using following code:
myControllerFunction(param1, collection, param3)
{
Ext.Msg.alert(collection.Order);
}
But it does not return anything. So please let me know how to resolve this problem!!
Any comment will appreciated!!
I'm not quite sure what it means "But it does not return anything", but I'll try.
So, your "DummyPanel" view have a alias or itemId property. In yor controller (in init() function), you need "keep track" of your view. For example:
In your view:
me.fireEvent('myEventName','Param1', fieldCollection, 'Param3');
In your controller:
init:function(){
var me = this;
this.control({
'panel[itemId=your-view-itemId]': { // call your function after event
myEventName: me.myControllerFunction
}
});
...
},
...
myControllerFunction: function(...) {
...
}
Should it not be
Ext.Msg.alert(collection["Order"])?
Or if you want to keep Ext.Msg.alert the way it is fieldCollection should be defined this way
var fieldCollection =
{
Order : 'ordNumber',
Ref : 'refNumber'
};

How to pass collection inside jeditable function?

I want to edit my collection using jeditable, where modifyCollection is a function associated with the event dblclick. I have the following code:
initialize : function(options) {
view.__super__.initialize.apply(this, arguments);
this.collection = this.options.collection;
this.render();
},
render : function() {
var template = _.template(tpl, {
collectionForTemplate : this.collection ,
});
this.el.html(template);
return this;
},
modifyCollection : function (event){
$('#name').editable(function(value, settings) {
return (value);
}
,
{ onblur: function(value) {
this.modelID=event.target.nameID;
this.collection = this.options.collection;
console.log("This Collection is: " + this.collection); //Shows : undefined
//
this.reset(value);
$(this).html(value);
return (value);
}
});
The idee is to update the model and subsequently, the collection by means of jeditable. The in place editing works fine, but the problem is, I am not able to pass the collection into the function. I want to save all the changes to my collection locally and send them to the server at a later time. What am I doing wrong here?
Moved the comment to a formal answer in case other people find this thread.
The this inside your onblur() function is not pointing to this collection. Try adding var self = this; inside your modifyCollection() function then in your onblur() change this.collection to self.collection like so:
modifyCollection : function (event) {
var self = this; // Added this line
// When working with functions within functions, we need
// to be careful of what this actually points to.
$('#name').editable(function(value, settings) {
return (value);
}, {
onblur: function(value) {
// Since modelID and collection are part of the larger Backbone object,
// we refer to it through the self var we initialized.
self.modelID = event.target.nameID;
self.collection = self.options.collection;
// Self, declared outside of the function refers to the collection
console.log("This Collection is: " + self.collection);
self.reset(value);
// NOTICE: here we use this instead of self...
$(this).html(value); // this correctly refers to the jQuery element $('#name')
return (value);
}
});
});
UPDATE - Foreboding Note on self
#muistooshort makes a good mention that self is actually a property of window so if you don't declare the var self = this; in your code, you'll be referring to a window obj. Can be aggravating if you're not sure why self seems to exist but doesn't seem to work.
Common use of this kind of coding tends to favor using that or _this instead of self. You have been warned. ;-)

Proper way to sort a backbone.js collection on the fly

I can successfully do this:
App.SomeCollection = Backbone.Collection.extend({
comparator: function( collection ){
return( collection.get( 'lastName' ) );
}
});
Which is nice if I want to have a collection that is only sorted by 'lastName'. But I need to have this sorting done dynamically. Sometimes, I'll need to sort by, say, 'firstName' instead.
My utter failures include:
I tried passing an extra variable specifying the variable to sort() on. That did not work. I also tried sortBy(), which did not work either. I tried passing my own function to sort(), but this did not work either. Passing a user-defined function to sortBy() only to have the result not have an each method, defeating the point of having a newly sorted backbone collection.
Can someone provide a practical example of sorting by a variable that is not hard coded into the comparator function? Or any hack you have that works? If not, a working sortBy() call?
Interesting question. I would try a variant on the strategy pattern here. You could create a hash of sorting functions, then set comparator based on the selected member of the hash:
App.SomeCollection = Backbone.Collection.extend({
comparator: strategies[selectedStrategy],
strategies: {
firstName: function () { /* first name sorting implementation here */ },
lastName: function () { /* last name sorting implementation here */ },
},
selectedStrategy: "firstName"
});
Then you could change your sorting strategy on the fly by updating the value of the selectedStrategy property.
EDIT: I realized after I went to bed :) that this wouldn't quite work as I wrote it above, because we're passing an object literal to Collection.extend. The comparator property will be evaluated once, when the object is created, so it won't change on the fly unless forced to do so. There is probably a cleaner way to do this, but this demonstrates switching the comparator functions on the fly:
var SomeCollection = Backbone.Collection.extend({
comparator: function (property) {
return selectedStrategy.apply(myModel.get(property));
},
strategies: {
firstName: function (person) { return person.get("firstName"); },
lastName: function (person) { return person.get("lastName"); },
},
changeSort: function (sortProperty) {
this.comparator = this.strategies[sortProperty];
},
initialize: function () {
this.changeSort("lastName");
console.log(this.comparator);
this.changeSort("firstName");
console.log(this.comparator);
}
});
var myCollection = new SomeCollection;
Here's a jsFiddle that demonstrates this.
The root of all of your problems, I think, is that properties on JavaScript object literals are evaluated immediately when the object is created, so you have to overwrite the property if you want to change it. If you try to write some kind of switching into the property itself it'll get set to an initial value and stay there.
Here's a good blog post that discusses this in a slightly different context.
Change to comparator function by assigning a new function to it and call sort.
// Following example above do in the view:
// Assign new comparator
this.collection.comparator = function( model ) {
return model.get( 'lastname' );
}
// Resort collection
this.collection.sort();
// Sort differently
this.collection.comparator = function( model ) {
return model.get( 'age' );
}
this.collection.sort();
So, this was my solution that actually worked.
App.Collection = Backbone.Collection.extend({
model:App.Model,
initialize: function(){
this.sortVar = 'firstName';
},
comparator: function( collection ){
var that = this;
return( collection.get( that.sortVar ) );
}
});
Then in the view, I have to M-I-C-K-E-Y M-O-U-S-E it like this:
this.collections.sortVar = 'lastVar'
this.collections.sort( this.comparator ).each( function(){
// All the stuff I want to do with the sorted collection...
});
Since Josh Earl was the only one to even attempt a solution and he did lead me in the right direction, I accept his answer. Thanks Josh :)
This is an old question but I recently had a similar need (sort a collection based on criteria to be supplied by a user click event) and thought I'd share my solution for others tackling this issue. Requires no hardcoded model.get('attribute').
I basically used Dave Newton's approach to extending native JavaScript arrays, and tailored it to Backbone:
MyCollection = Backbone.Collection.extend({
// Custom sorting function.
sortCollection : function(criteria) {
// Set your comparator function, pass the criteria.
this.comparator = this.criteriaComparator(criteria);
this.sort();
},
criteriaComparator : function(criteria, overloadParam) {
return function(a, b) {
var aSortVal = a.get(criteria);
var bSortVal = b.get(criteria);
// Whatever your sorting criteria.
if (aSortVal < bSortVal) {
return -1;
}
if (aSortVal > bSortVal) {
return 1;
}
else {
return 0;
}
};
}
});
Note the "overloadParam". Per the documentation, Backbone uses Underscore's "sortBy" if your comparator function has a single param, and a native JS-style sort if it has two params. We need the latter, hence the "overloadParam".
Looking at the source code, it seems there's a simple way to do it, setting comparator to string instead of function. This works, given Backbone.Collection mycollection:
mycollection.comparator = key;
mycollection.sort();
This is what I ended up doing for the app I'm currently working on. In my collection I have:
comparator: function(model) {
var methodName = applicationStateModel.get("comparatorMethod"),
method = this[methodName];
if (typeof(method === "function")) {
return method.call(null, model);
}
}
Now I can add few different methods to my collection: fooSort(), barSort(), and bazSort().
I want fooSort to be the default so I set that in my state model like so:
var ApplicationState = Backbone.Model.extend({
defaults: {
comparatorMethod: "fooSort"
}
});
Now all I have to do is write a function in my view that updates the value of "comparatorMethod" depending upon what the user clicks. I set the collection to listen to those changes and do sort(), and I set the view to listen for sort events and do render().
BAZINGA!!!!

Resources