Using Titanium, Remove current view or pop current view - javascript

I have to remove current view being in the same view...
if i am in the parent view i can do
parentView.remove(childView);
but being on the child view i am not having parentView so how can i pop childView to get parentView on top, as it happens on pressing the back button in iOS??
please help
Here is my childView file..
function DetailView(){
var self = Ti.UI.createView({
backgroundColor:'#fff'
});
// Create a Button.
var aButton = Ti.UI.createButton({
title : 'aButton',
height : '50',
width : '100',
top : '10',
left : '20'
});
// Listen for click events.
aButton.addEventListener('click', function() {
alert('\'aButton\' was clicked!');
I have to navigate back on press of aButton, what should i Put here to do that
});
// Add to the parent view.
self.add(aButton);
return(self);
}
module.exports = DetailView;
Here is my parent view:
//FirstView Component Constructor
var self = Ti.UI.createView();
function FirstView() {
//create object instance, a parasitic subclass of Observable
var DetailView = require('ui/common/DetailView');
var data = [{title:"Row 1"},{title:"Row 2"}];
var table = Titanium.UI.createTableView({
data:data
});
table.addEventListener('click', rowSelected);
self.add(table);
return self;
}
function rowSelected()
{
var DetailView = require('ui/common/DetailView');
//construct UI
var detailView = new DetailView();
self.add(detailView);
}
module.exports = FirstView;

You can pass your parentView to the constructor of child view at this point:
//construct UI
var detailView = new DetailView(parentView);
self.add(detailView);
and in click event
aButton.addEventListener('click', function() {
if ( parentView != null ) {
parentView.remove(childView);
}
});

Related

Open Layer, deactive ol.control.Toggle and active another one

I have an ol.control.Bar built as below:
mainbar = new ol.control.Bar ({ toggleOne: true, group:true });
var me = this;
// Function with its level context
function addButton(level) {
var levelButton = new ol.control.Toggle({
html: level,
onToggle: function () {
me.getController().updateFloorplans(level);
}
});
mainbar.addControl (levelButton);
}
// Insert buttons
var indexFloor = 4;
while(indexFloor > 0){
addButton(indexFloor);
indexFloor--;
};
addButton('0');
mainbar.setPosition('bottom-right');
this.map.addControl(mainbar);
I would like to create a function that deactive the buttons in the ol.control.Bar (for example the 3 in the image) and active another button choose by me (ad example the button 2).
How I can do that?
I created this function, but instead to deactivate all the buttons that are active, it remove all the control bar:
deactiveButtons: function(){
var self = this;
self.map.removeControl(mainbar);
},

Uncaught TypeError: Cannot read property 'style' of null / Oracle JET

Hello I'm a beginner in JS and Oracle JET Framework.
I'm trying to implement a Panel Expand/Collapse item in my project (http://www.oracle.com/webfolder/technetwork/jet-310/jetCookbook.html?component=animation&demo=panelExpand) and I have this error I don't know why I followed the cookbook. Here is my code :
My HTML :
<div id="animationDemo">
<div id="panel" class="oj-panel oj-margin basepanel">
<h3>Panel Expand/Collapse Demo</h3>
<div>Primary Content</div>
<div id="extra-content" class="oj-panel oj-panel-alt2 childpanel">Extra Content</div>
<button class="oj-panel-resize-button"
data-bind="click: buttonClick,
ojComponent: {component: 'ojButton',
chroming: 'half',
display: 'icons',
icons: buttonIcons,
label: buttonLabel}"></button>
</div>
</div>
My JS
define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout',
'promise', 'ojs/ojtable', 'ojs/ojarraytabledatasource','ojs/ojbutton', 'ojs/ojanimation'],
function(oj, ko, $) {
function CustomerViewModel() {
var self = this;
////
var panel = document.getElementById('panel');
var extra = document.getElementById('extra-content');
var initHeight = $(panel).css('height');
// Keep track of whether the element is expanded
self.expanded = false;
self.buttonIcons = ko.observable({end:'oj-panel-expand-icon'});
self.buttonLabel = ko.observable('expand');
self.buttonClick = function() {
if (self.expanded) {
// Call the collapse method, then hide the extra content when animation ends.
oj.AnimationUtils['collapse'](panel, {'endMaxHeight': initHeight}).then(function() {
extra.style.display = 'none';
self.expanded = false;
self.buttonIcons({end:'oj-panel-expand-icon'});
self.buttonLabel('expand');
});
} else {
// Mark the extra content to be displayed, followed by a call to the expand method.
extra.style.display = 'block';
oj.AnimationUtils['expand'](panel, {'startMaxHeight': initHeight}).then(function() {
self.expanded = true;
self.buttonIcons({end:'oj-panel-collapse-icon'});
self.buttonLabel('collapse');
});
}
};
///
self.connected = function() {
// Implement if needed
};
self.disconnected = function() {
// Implement if needed
};
self.transitionCompleted = function() {
};
self.hello2 = function() {
alert('hhhh');
};
}
return new CustomerViewModel();
}
);
Thank you for your help
It's because the HTML hasn't loaded yet when it comes to these lines:
var panel = document.getElementById('panel');
var extra = document.getElementById('extra-content');
var initHeight = $(panel).css('height');
So their values become null.
Instead, you could call them only after the document has loaded using jQuery, like this:
var panel;
var extra;
var initHeight;
$(document).ready(function(){
panel = document.getElementById('panel');
extra = document.getElementById('extra-content');
initHeight = $(panel).css('height');
});
Or if you want to do it the pure OJET way, you could do this:
var panel;
var extra;
var initHeight;
self.handleBindingsApplied = function(){
panel = document.getElementById('panel');
extra = document.getElementById('extra-content');
initHeight = $(panel).css('height');
};
self.handleBindingsApplied is an internal method of an OJET Viewmodel that gets called automatically after the binding between the HTML and Viewmodel is complete.
You can read more about all the internal methods here.
P.S. don't forget to apply the CSS as well from the cookbook.

backbone drag and drop - getting dropped data

I'm relatively new to programming and this is my first time posting on here, so sorry in advance if this isn't presented correctly.
I'm building a health tracker app with Backbone JS. I am retrieving data from the Nutritionix API and populating a view on the left side of the screen with that data. I want the user to be able to drag an item from the populated view and drop it in a view to the right in which case a calorie counter will increase. I also need that data to persist so that when the user closes and reopens the app their selected data in the view will remain the same.
I've implemented the drag and drop feature just fine. I am now trying to make it so that when the user drops an item from the left view into the right view a collection is created that only contains the data in the right view. I believe that I need to do this so I can persist the data. Right now, I am having trouble transferring the API data along into the right view. Here are the relevant code snippets:
appView:
var app = app || {};
var ENTER_KEY = 13;
app.AppView = Backbone.View.extend({
el: '#health-app',
urlRoot: 'https://api.nutritionix.com/v1_1/search/',
events: {
'keypress': 'search',
'click #clearBtn': 'clearFoodList',
'drop .drop-area': 'addSelectedFood',
// 'drop #selected-food-template': 'addSelectedFood'
},
initialize: function() {
this.listenTo(app.ResultCollection, 'add', this.addFoodResult);
// this.listenTo(app.SelectedCollection, 'add', this.addSelectedFood);
app.ResultCollection.fetch();
app.SelectedCollection.fetch();
this.clearFoodList()
},
addFoodResult: function(resultFood) {
var foodResult = new SearchResultView({
model: resultFood
});
$('#list').append(foodResult.render().el);
},
// addSelectedFood: function(selectedFood) {
// // var selectedFoodCollection = app.SelectedCollection.add(selectedFood)
// console.log(app.SelectedCollection.add(selectedFood))
// },
clearFoodList: function() {
_.invoke(app.ResultCollection.toArray(), 'destroy');
$('#list').empty();
return false;
},
search: function(e) {
var food;
//When the user searches, clear the list
if($('#search').val() === '') {
_.invoke(app.ResultCollection.toArray(), 'destroy');
$('#list').empty();
}
//Get the nutrition information, and add to app.FoodModel
if (e.which === ENTER_KEY) {
this.query = $('#search').val() + '?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=be7425dc&appKey=c7abd4497e5d3c8a1358fb6da9ec1afe';
this.newUrl = this.urlRoot + this.query;
var getFood = $.get(this.newUrl, function(data) {
var hits = data.hits;
var name, brand_name, calories, id;
_.each(hits, function(hit){
name = hit.fields.item_name;
brand_name = hit.fields.brand_name;
calories = hit.fields.nf_calories;
id = hit.fields.item_id;
food = new app.FoodModel({
name: name,
brand_name: brand_name,
calories: calories,
id: id
});
//If the food isn't in the ResultCollection, add it.
if (!app.ResultCollection.contains(food)) {
app.ResultCollection.add(food);
}
});
food.save();
});
}
}
});
breakfastView:
var app = app || {};
app.BreakfastView = Backbone.View.extend({
el: '#breakfast',
attributes: {
'ondrop': 'ev.dataTransfer.getData("text")',
'ondragover': 'allowDrop(event)'
},
events: {
'dragenter': 'dragEnter',
'dragover': 'dragOver',
'drop': 'dropped'
},
initialize: function() {
this.listenTo(app.SelectedCollection, 'change', this.addSelectedFood);
},
render: function() {},
addSelectedFood: function(selectedFood) {
// var selectedFoodCollection = app.SelectedCollection.add(selectedFood)
console.log(app.SelectedCollection.add(selectedFood))
},
dragEnter: function (e) {
e.preventDefault();
},
dragOver: function(e) {
e.preventDefault();
},
dropped: function(ev) {
var data = ev.originalEvent.dataTransfer.getData("text/plain");
ev.target.appendChild(document.getElementById(data));
// console.log(app.SelectedCollection)
this.addSelectedFood(data);
},
});
new app.BreakfastView
SelectedCollection:
var app = app || {};
app.SelectedCollection = Backbone.Collection.extend({
model: app.FoodModel,
localStorage: new Backbone.LocalStorage('selected-food'),
})
app.SelectedCollection = new app.SelectedCollection();
Here's my repo also, just in case: https://github.com/jawaka72/health-tracker-app/tree/master/js
Thank you very much for any help!

Knockout.js Unobtrusive event handler not working

Here is I have table built with knockout 'foreach'. After user select some rows, these rows will contain class 'success'. So I want to use self.create event that fire after user press button (button located outside element that ViewModel binded to) in order to handle such table rows. But Firebug said: TypeError: GrafikViewModel.books is undefined.
Here is the code:
function InfoViewModel(baseUri) {
//some viewmodel here
}
//This is viewmodel I'm talking about.
function GrafikViewModel(grafikUri) {
var self = this;
self.books = ko.observableArray();
self.create = function () {
//Here we will handle tr with class 'success'
alert("!!!");
}
$.getJSON(grafikUri, function (data) {
self.books(data.$values);
});
}
$(document).ready(function () {
var url = location.href.split("/");
var baseUri;
var tkod = url[5];
if (url[4].toString = 'x') {
baseUri = '/api/xTourist/' + tkod;
}
else if (url[4].toString = 'y') {
baseUri = '/api/yTourist/' + tkod;
}
var grafikUri = '/api/grafik/' + tkod;
ko.applyBindings(InfoViewModel(baseUri), document.getElementById('info'));
ko.applyBindings(new GrafikViewModel(grafikUri), document.getElementById('grafik'));
$('#book').click(function () {
//Here I'm trying to call ViewModel.
GrafikViewModel.books.create(ko.dataFor(this));
});
});
try new GrafikViewModel().books.create(ko.dataFor(this));

Zombie views and events in Backbone marionette layout... Have I got them?

I think I might have a problem with zombie views in my Backbone Marionette app.
How can I check for unclosed views and memory leaks? I'm using the illuminations-for-developers.com add-on for Firefox and as I move around my application I see over 1000 views piling up in the 'widgets' illuminations tab - and when I inspect the HTML for them the majority are not in the DOM. Are these zombied views?
Have added the code I'm using below to get peoples opinion on if I'm attacking the problem the right way.
I'm trying to build a UI similar to the Facebook multiple friend selector dialog (see pic).
I have a layout with two collection views, one populated with a list of users, and an empty one in which the selected users are added to.
I want to use this layout in multiple areas of my app. So I have built a controller object that handles initializing it and loading the data for the collections, and then I initialize it and show it in another region whenever it is required.
Would appreciate tips on how to go about this, thanks.
Codez:
MyApp.UserFilterController
MyApp.UserFilterController = (function(){
var UserFilterController = {};
var selectedUsersCol;
var userFilterColView;
var selectedUsersColView;
var usersCol;
UserFilterController.initialize = function ( callback, excludeUsers ) {
// make a query...
// exclude the users...
var usersQ = new Parse.Query(Parse.User);
// just users with email addresses
usersQ.exists('email');
usersQ.exists('name');
usersQ.limit(1000);
usersQ.ascending('name');
usersQ.notContainedIn('objectId',excludeUsers);
usersCol = usersQ.collection();
// tell it where to render... append to the body give it an element?
userFilterColView = new MyApp.UserFilterUserCollectionView({
collection:usersCol
});
usersCol.fetch({
success:function (col) {
console.log("users collection fetched", col.length);
},
error:function () {
console.log("error fetching users collection");
}
});
$('#subpage-header').text("Users Selection");
// empty collection to hold the selected users
selectedUsersCol = new MyApp.Users();
// view to show the selected users
selectedUsersColView = new MyApp.SelectedUserCollectionView({
collection:selectedUsersCol
});
_.extend(selectedUsersCol, newBackboneAddMethod());
MyApp.userFilterLayout = new MyApp.UserFilterLayout();
MyApp.slideUp.content.show(MyApp.userFilterLayout);
MyApp.userFilterLayout.selectedusers.show(selectedUsersColView);
MyApp.userFilterLayout.allusers.show(userFilterColView);
//When user clicks on user in all users then its added to selected users
userFilterColView.on("itemview:clicked", function(childView, model){
console.log(model);
selectedUsersCol.add(model);
});
userFilterColView.on("collection:rendered", function(childView, model){
console.log('its rendered');
});
//When user clicks on selected user then it is removed from the collection
selectedUsersColView.on("itemview:clicked", function(childView, model){
console.log(model);
console.log(model.id);
selectedUsersCol.remove(model);
});
MyApp.App.vent.bind("slideUp:send",function(){
console.log("send button has been clicked. attempting call back")
callback(selectedUsersCol);
});
//unbinds the trigger above when view is being closed
userFilterColView.on('collection:before:close', function (){
MyApp.App.vent.unbind("slideUp:send");
console.log('colView before:close')
});
};
UserFilterController.removeUser = function ( user ) {
//console.log("you asked to remove", usersArray.length, 'users');
selectedUsersCol.remove(user);
usersCol.remove(user);
};
UserFilterController.generateListview = function ( user ) {
userFilterColView.$el.listview();
};
UserFilterController.resetSelected = function (user) {
selectedUsersCol.reset();
};
UserFilterController.cleanup = function () {
console.log("its closing");
//selectedUsersColView.unbindAll();
// selectedUsersColView.close();
userFilterColView.close();
// userFilterLayout.unbindAll();
// MyApp.userFilterLayout.close();
// MyApp.slideUp.content.close();
// MyApp.slideUp.close();
};
return UserFilterController;
}());
MyApp.EventDisplayLayout
MyApp.EventDisplayLayout = Backbone.Marionette.Layout.extend({
template: '#event-display-layout',
id: "EventDisplayLayout",
events: {
'click #invite': 'showUserFilter'
},
// User clicked on 'invite' button
showUserFilter: function () {
$.mobile.changePage($('#subpage'), {changeHash: false,transition: 'slideup'});
MyApp.UserFilterController.generateListview();
}
}
MyApp.showEventDisplay
MyApp.showEventDisplay = function (event) {
var eventDisplayLayout = new MyApp.EventDisplayLayout({});
MyApp.App.mainRegion.show(eventDisplayLayout);
var Invitees = event.get("invitees");
var excludeIds = [];
_.each(Invitees,function(invitee){
excludeIds.push(invitee.id);
});
MyApp.UserFilterController.initialize(function (selectUsersCol){
console.log("In call back: ",selectUsersCol);
},excludeIds);
};
MyApp.SlideUpPageLayout
// The generic layout used for modal panel sliding up from bottom of page.
MyApp.SlideUpPageLayout = Backbone.Marionette.Layout.extend({
el: '#subpage',
//template: '#homepage-temp',
regions: {
header: '.header',
content: '.content'
},
events:{
'click .send':'slideUpSend',
'click .cancel':'slideUpCancel'
},
onShow: function () {
console.log("SlideUpPage onShow");
this.$el.trigger('create');
},
initialize: function () {
// make user collection...
},
slideUpSend: function () {
console.log("send button has been pressed");
MyApp.App.vent.trigger('slideUp:send');
$.mobile.changePage($('.type-home'),{transition: 'slideup',reverse:true});
},
slideUpCancel: function () {
// MyApp.App.vent.trigger('slideUp:cancel');
$.mobile.changePage($('.type-home'),{transition: 'slideup',reverse:true});
}
});
MyApp.UserFilterLayout
// The layout used for the user filter panel sliding up from bottom of page.
MyApp.UserFilterLayout = Backbone.Marionette.Layout.extend({
template: '#userfilterlayout',
//template: '#homepage-temp',
regions: {
selectedusers: '.selectedusers',
allusers: '.allusers'
},
onShow: function () {
console.log("userfilterlayout onShow");
this.$el.trigger('create');
}
});

Categories