Hi guys
I have a commonJS file that looks after the data and presentation for a trip. I can create and display the view okay. What I want to do now is add a new view within the top view, but I get a TypeError.
The top-level function, ridesWindow, simply create the rideComponent object, and then calls the rideComponent.show() function to create the UI. The rideComponent.getMainView() is then used to retrieve the top level view from the RideComponent object, and added to win.
As part of the show() function, a event listener is created that will call expandTrip if rideComponent is clicked at all, and, as expected, this does get called correctly. In expandTrip, a new view is created and added to the top level view.
Now the problem, I get the error "Uncaught TypeError: cannot call method 'add' of undefined" with the source listed as "this.rideComponent.add(extendedView)". I have tried a number of different approaches, but I can't get past this problem.
Thanks for any help, Richard
function ridesWindow() { var rideComponent = require('ui/handheld/RideComponent'); var win = Titanium.UI.createWindow ({ layout:'vertical' }); this.myRide = new rideComponent('driver', 'Party with Dave'); this.myRide.show(); win.add(this.myRide.getMainView()); }
function RideComponent(type, title) { this.title = title; this.type = type; } RideComponent.prototype.show = function() { this.rideComponent = Ti.UI.createView ({ layout:'vertical' }); var titleText = Titanium.UI.createLabel ({ text:this.title }); var tripTypeImage = Ti.UI.createImageView ({ image :'/image/driver.png' }); this.rideComponent.add(titleText); this.rideComponent.add(TypeImage); this.rideComponent.addEventListener('click', this.expandTrip); } RideComponent.prototype.getMainView = function(){ return this.rideComponent; } RideComponent.prototype.expandTrip = function(e) { var extendedView = Ti.UI.createView ({ layout:'vertical', }); this.rideComponent.add(extendedView); } module.exports = RideComponent;
1 Answer
Accepted Answer
Hi Richard,
Function expandTrip() is called through an event handler. In this context, the "this" pointer does not point to the object in which the function has been defined. This is an oddity of the Javascript language definition.
A common workaround is to save the "this" pointer into another variable and refer to it from a closure. In your case, try changing expandTrip into a closure defined within addEventListener. Then assign "this" to "that" and refer to "that" from the body of the closure:
var that = this; this.rideComponent.addEventListener('click', function(e) { var extendedView = Ti.UI.createView ({ layout:'vertical', }); that.rideComponent.add(extendedView); });Closures can take their "outer" context with them, so "that" will still be pointing to the current object when the closure is called later through an event.
Regards,
Christoph
Your Answer
Think you can help? Login to answer this question!