Backbone.Events context issue in Appcelerator Titanium - backbone.js

I have a custom library in my Titanium Mobile (3.1.0 GA SDK) project that looks something like this:
// lib/MyObject.js
function MyObject
{
var self = this;
_.extend(self, Backbone.Events);
this.trigger('myEvent');
}
module.exports = MyObject;
In another part of my application, I make the class available globally:
Alloy.Globals.MyObject = require('MyObject');
And in a controller, I instantiate it:
var myObj = new Alloy.Globals.MyObject();
That object gets passed around a bit, until finally an event listener is added:
// In another controller
myObj.on('myEvent', function() {
console.log('My event happened!');
};
Unfortunately, log command never gets called. If I add an event listener within the MyObject function, it works fine. But it won't work when called from outside the object.
I would just assume that there's a bug in there, or the object is getting passed by value instead of reference, except for this. If I change the class definition to the following:
// lib/MyObject.js
function MyObject
{
var self = this;
_.extend(self, Backbone.Events);
var old_on = this.on;
this.on = function(a, b, c) {
return old_on.call(self, a, b, c);
};
this.trigger('myEvent');
}
module.exports = MyObject;
...everything works. Somehow the on function is not getting the correct context, but I can't for the life of me figure out why. Anyone have insight into what's going on?

Hmm, updating to the 3.1.1.GA SDK version fixed it. Must've been a bug in Titanium.

Related

How to properly save self reference with ES6 classes?

Honestly, I'm not sure of what is the cause for the behavior: systemjs, babel or my own fault. I'm using class for custom control controller and saving class reference in self variable. Apparently that gets overriden by any subsequent controller instances.
I created a simple repository to demonstrate:
clone, install, run live-server or your preferred server. You will see 2 buttons, each is a custom control. Clicking on a button only affects one control.
https://github.com/alexkolt/selfIsThis
How can I get this working with ES6 class?
I should have posted the code, sorry.
The reason you'd want to save reference to self is for example in callbacks calling this might result in a different reference.
I was trying to do this:
var self;
class Test {
constructor(dependency) {
self = this;
self.dependency = dependency;
}
method() {
self.dependency().then(value => self.property = value);
}
}
Like it was mentioned before the self becomes shared when declared outside of the module. I didn't realize that would happen as files would be wrapped in a closure. Joe Clay answer is correct, but to do what I was trying to do self needs to be declared in every method that needs it.
class Test {
constructor(dependency) {
this.dependency = dependency;
}
method() {
var self = this;
this.dependency().then(value => self.property = value);
}
}
You're not really using ES6 classes right. You don't need to save a reference to this - just access it directly in class methods. The way you have it at the minute, all your instances of CustomControlController are sharing a single self variable.
class CustomControlController {
constructor() {
this.value = 0;
}
click() {
var newValue = this.value * 2;
this.value = newValue;
}
}
export default CustomControlController;

How to apply a partial update to an object using AngularFire

The $save() in Angularfire 0.8 is confusing me.
Here's a minimal example - a snippet from my controllers.js file:
.controller('LandingPageController', ['$scope','$firebase', function($scope,$firebase) {
$scope.addNode = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/');
var fbr = $firebase(FB);
fbr.$set(1,{firstname: 'James'});
}
$scope.addAttribute = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
var fbr = $firebase(FB).$asObject();
fbr.lastname = "Bond";
fbr.$save();
}
}])
When addNode() is called, sure enough, a node is created in my firebase:
But when addAttribute() is called, the entire record is replaced, rather than what I expected, which was for the 'lastname' attribute to be added.
I've no doubt misunderstood the docs. Can anyone help?
Update:
OK, I needed to wait until the object was loaded. It works now, after changing addAttribute to:
$scope.addAttribute = function() {
var FB = new Firebase('https://protodb.firebaseio.com/testrecords/1');
var fbr = $firebase(FB).$asObject();
fbr.$loaded().then(function() {
fbr.lastname = "Bond";
fbr.$save();
});
}
As you found out yourself already:
a FirebaseObject (as returned by $asObject()) does not have a $update method.
when you call $save() on a FirebaseObject before it is completely loaded, you may end up deleting other properties
To patch existing data you can:
Either wait for the entire object to be loaded (as you did in your update to the question)
Or call $firebase.$update directly
$firebase(FB).$update({ lastname: "Bond" });
This last approach has the advantage that you don't pull down the entire object, only to update a single property. Note that this is probably premature optimization in most cases, but still...

How do you tell when a view is loaded in extjs?

Im working on an extjs application. We're have a page that is for looking at a particular instance of an object and viewing and editing it's fields.
We're using refs to get hold of bits of view in the controller.
This was working fine, but I've been sharding the controller into smaller pieces to make it more managable and realised that we are relying on a race condition in our code.
The logic is as follows:
Initialise the controller
parse the url to extract the id of the object
put in a call to load the model with the given view.
in the load callback call the controller load method...
The controller load method creates some stores which fire off other requests for bits of information using this id. It then uses some of the refs to get hold of the view and then reconfigures them to use the stores when they load.
If you try and call the controller load method immediately (not in the callback) then it will fail - the ref methods return undefined.
Presumably this is because the view doesnt exist... However we aren't checking for that - we're just relying on the view being loaded by the time the server responds which seems like a recipe for disaster.
So how can we avoid this and be sure that a view is loaded before trying to use it.
I haven't tried rewriting the logic here yet but it looks like the afterrender event probably does what I want.
It seems like waiting for both the return of the store load and afterrender events should produce the correct result.
A nice little abstraction here might be something like this:
yourNamespace.createWaitRunner = function (completionCallback) {
var callback = completionCallback;
var completionRecord = [];
var elements = 0;
function maybeFinish() {
var done = completionRecord.every(function (element) {
return element === true
});
if (done)
completionCallback();
}
return {
getNotifier: function (func) {
func = func || function (){};
var index = elements++;
completionRecord[index] = false;
return function () {
func(arguments);
completionRecord[index] = true;
maybeFinish();
}
}
}
};
You'd use it like this:
//during init
//pass in the function to call when others are done
this.waiter = yourNamespace.createWaitRunner(controller.load);
//in controller
this.control({
'SomeView': {
afterrender: this.waiter.getNotifier
}
});
//when loading record(s)
Ext.ModelManager.getModel('SomeModel').load(id, {
success: this.waiter.getNotifier(function (record, request) {
//do some extra stuff if needs be
me.setRecord(record);
})
});
I haven't actually tried this out yet so it might not be 100% but I think the idea is sound

Extending Backbone Collections to add logic, with custom methods, is a bad practice?

Usually I find my self needing to write an object with a specific functionality that it is a set of models.
Finally I extend a collection and add more functions that works with its model.
I think is better show you an example:
My app has a set of permissions, related with the user and/or the version of the platform.
var Permissions = Backbone.Collection.extend({
model: Permission,
hasAccess: function (moduleCode) {
....
},
allowAccess: function (moduleCode) {
....
},
...
With that methods I change the format of a property of a permission (the model). (My permissions are a concatenation of code with an string that identify the type of permission.)
A workmate tells me that it is wrong. In .NET he creates a class and he adds a private list and makes the changes to it. He does not inherit the list and changes it.
He would make a model and inside it he would add a collection property
this.set("permissionsCollection", new Backbone.Collection.extend({model: Permission}))
[Comment: I don't understand why he creates properties of everything, I think in his case it is not needed.] -> But this is another question
I think in a different way. I know the Collection has internally that list. I have a great potencial in Backbone.Collections, why do I have to use a model that it is not necessary? If I don't need that encapsulation... I think that it is not necessary, he is overprogramming in my opinnion.
Am I wrong? Did I not know how to use BackboneJS Collections?
Thank you in advance.
At the beginning I had something called helper with similar methods:
findAttr: function (model, name) {
var attrs = model.get('app_attrs');
if (attrs !== undefined) {
return this.findByAttrName(attrs, name);
}
},
findByAttrName: function (array, name) {
return _.find(array, function(a) {
if (a.attrName === name) {
return a;
}
});
}
The view code was more awkward:
render: function () {
var attr = helper.findAttr(this.model, 'user');
...
return this;
}
The only logical solution was to move these methods into the model (this.model in the above case). After refactoring I've got:
render: function () {
var attr = this.model.findAttr('user');
...
return this;
}
which is of course more readable than the previous solution.

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. ;-)

Resources