What does this BlackBerry Web App Javascript code do? - javascript

I know my way around several programming languages but am struggling understanding Javascript and how it's used in mobile apps. I'm developing for BlackBerry and a using the BlackBerry 10 jQuery Mobile Theme. I'm looking at the App.js from the samples and am confused as to what the App object is.
App = {};
App.init = function () {
console.log("App Init");
App.utils.metaHack();
$("#activity").live("pageinit", function(){
App.page.activity.init();
});
$("#bb_activity").live("pageinit", function(){
App.page.bb_activity.init();
});
$("#progressPage").live("pageinit", function(){
App.page.progress.init();
});
$("#sliderPage, #sliderPageDark").live("pageinit", function(){
App.page.slider.init();
});
$("#togglePage, #togglePageDark").live("pageinit", function(){
App.page.toggle.init();
});
$("#actionBarSample").live("pageinit", function() {
App.page.actionBarSample.init();
});
$('#applicationMenu').live("pageinit", function() {
App.page.applicationMenu.init();
});
}
App.utils = {
metaHack: function () {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
}
}
App.page = {
activity: {},
bb_activity: {},
progress: {},
slider: {},
toggle: {},
actionBarSample: {},
applicationMenu: {}
}
App.page.activity.init = function() {
$('#show').on('click', function () {
$.mobile.loading('show');
});
$('#text').on('click', function() {
$.mobile.loading('show', {
text: 'Loading',
textVisible: true,
textonly: true,
theme: 'a'
});
});
$('#swatch-a').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'a'
});
});
$('#swatch-a-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'a'
});
});
$('#swatch-c').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'c'
});
});
$('#swatch-c-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'c'
});
});
$('#hide').on('click', function () {
$.mobile.loading('hide');
});
}
App.page.bb_activity.init = function() {
console.log("bb_activity");
$('#throttle').on('change', function () {
console.log("throttle");
var speed = $('#throttle').val();
$('#speedTest').activityindicator('speed', speed+'s');
});
}
App.page.progress.init = function() {
var p = 0;
var error = pause = false;
function watchProgress() {
if( p > 100 || error || pause) {
return;
}
$('#rogress').progressbar("setValue", p);
p+= 4;
setTimeout(watchProgress, 100);
}
$('#start').on('vclick', function () {
error = false;
watchProgress();
});
$('#error').on('vclick', function () {
$('#rogress').progressbar("setError", error = !error);
});
$('#pause').on('vclick', function () {
$('#rogress').progressbar("pause", pause = !pause);
});
$('#reset').on('vclick', function () {
p = 0;
error = pause = false;
$('#rogress').progressbar("setValue", p);
});
}
App.page.slider.init = function() {
$('#slider-disabled').slider('disable');
$('#slider-disabled-highlight').slider('disable');
}
App.page.toggle.init = function() {
console.log("toggle init");
$('#flip-disabled').slider('disable');
}
App.page.actionBarSample.init = function() {
var $tabo = $("#tover"),
overflowState = $tabo.hasClass("noContent");
$("#left").on("panelbeforeopen", function() {
//Save the state of the overflow button
overflowState = $tabo.hasClass("noContent");
$tabo.addClass("noContent");
})
.on("panelbeforeclose", function() {
//Put the overflow button into the correct state
if(!overflowState) {
$tabo.removeClass("noContent");
}
});
//Handle overflow menu clicks
$(".bb10-panel").bind("vclick", function() {
//Close the panel
$(this).panel("close");
});
$("#left li").bind("vclick", function() {
//Clear the active state from any other buttons that may have been set to active
$(this).siblings().removeClass("ui-btn-active");
//Add the active state to the selected button
$(this).addClass("ui-btn-active");
//Clear the contents of the tab overflow button
//Add class to put the tab overflow icon in the correct position
//Clear the active state from all tab buttons in action bar
$('[data-role="tab"], [data-role="tab-overflow"]').removeClass("active");
});
$(".inBar").bind("vclick", function() {
//Set the active state to the tab in the actionbar
$('#' + this.id.slice(0, 2)).addClass("active");
$tabo.addClass("noContent").empty();
overflowState = true;
});
$(".notInBar").bind("vclick", function() {
//Set the active state to the tab overflow button
$tabo.empty()
.addClass("active")
.html('<img src="img/generic_81_81_placeholder.png" alt=""><p>' + $(this).text() + '</p>')
.removeClass("noContent");
overflowState = false;
});
$("[data-role='tab']").bind("vclick", function() {
//Change page on tab click
if($(this).data("href")) {
$.mobile.changePage( $(this).data("href"), { transition: "slideup"} );
}
});
}
App.page.applicationMenu.init = function() {
if(typeof blackberry != 'undefined'){
blackberry.event.addEventListener('swipedown', function(){
$('#top').panel("open");
});
$('#menuBtn').css('display','none');
}
else{
$('#simulInst').css('display','none');
}
}
App.init();
Is App an object specific to Blackberry? I did some dabbling and made a small app but didn't use App or init anything.

App in this example is defined at the top:
App = {};
So it's just a new plain old JavaScript object (dictionary), which they then define functions and data to it e.g. App.utils = ....
You can try it out on a browser, press F12 and then go to the console (ESC) and type e.g. blah = {} and you will see a new object created with the name blah. Everything is an object in JavaScript apparently.
Read more
http://www.w3schools.com/js/js_objects.asp

Related

using bootstrap 3.37 header dropdown menu and tranlsating jquery to knockoutJS

I was looking at this article to apply header menu with dropdowns in my mvc5 knockoutjs solution.
https://jdmdigital.co/news/codex/bootstrap-3-secondary-dropdown-menu/
The frontend it looks nice, and it is ok in my solution, however, I cant figure it out how to bind js section to work.
Now when I click on my dropdown parent item, nothing happens, because the js code is not working.
here is my setup of the js (knockoutjs) file.
define(['durandal/system', 'plugins/router', 'durandal/services/logger', 'knockout', 'common', 'plugins/dialog', 'durandal/binder', 'fastclick'],
function (system, router, logger, ko, common, dialog, binder, fs) {
var shell = {
activate: activate,
router: router,
};
// Make Dropdown Submenus possible
$('.dropdown-submenu a.dropdown-submenu-toggle').on("click", function (e) {
$('.dropdown-submenu ul').removeAttr('style');
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
// Clear Submenu Dropdowns on hidden event
$('#bs-navbar-collapse-1').on('hidden.bs.dropdown', function () {
$('.navbar-nav .dropdown-submenu ul.dropdown-menu').removeAttr('style');
});
//...
//...
//OTHER INIT METHODS (not in the scope for this question)
//#region Internal Methods
function activate() {
var result = registerRoutes();
//setRouteGuard();
if (window.cordova) {
window.document.addEventListener("deviceready", function () {
shell.refreshUserData(true);
shell.changeLanguage();
});
} else {
shell.refreshUserData(true);
shell.changeLanguage();
}
shell.isLoading.subscribe(function (newValue) {
//if something gone wrong
if (newValue) {
setTimeout(function () {
//shell.isLoading(false);
}, 10000);
}
});
if (router.activeInstruction().config.moduleId == "viewmodels/parentschedule") {
if (shell.isAnonymousUser() == true) {
shell.isClient(false);
shell.isEmployee(false);
}
else {
shell.isClient(true);
shell.isEmployee(true);
}
//console.log("test");
}
return result;
}
function route(r, moduleId, name, visible, alwaysVisible, role, condition) {
var self = this;
self.route = r;
self.moduleId = moduleId;
self.title = name;
self.visible = visible;
self.nav = true;
self.role = role;
self.condition = condition;
self.mouseover = ko.observable(false);
self.onhover = function () {
self.mouseover(!self.mouseover());
};
self.goToPage = function () {
router.navigate(this.hash);
};
self.alwaysVisible = alwaysVisible;
self.isTouched = ko.observable(false);
self.setTouched = function () {
self.isTouched(true);
return true;
}
self.setUnTouched = function () {
setTimeout(function () {
self.isTouched(false);
}, 200);
return true;
}
self.isActiveMenuItem = ko.computed(function () {
return router.activeInstruction() &&
router.activeInstruction().fragment.indexOf(self.route) > -1
});
return self;
}
//#endregion
});

How to properly add multiple elements event in jQuery custom plugin

I am trying to write my first jquery plugin and I'm having some difficulties trying to implement functions, events and triggers.
Here is the scenario in which I'm working.
I've multiple input box with same class eg. "numberTextBox"
Apply plugin directly to these classes eg. "$(".numberTextBox").inputNumericTextBox();".
I can also give settings in it.
Now plugin should allow only numeric value based on setting either given on default.
what I had in my mind is to properly convert and verify any given value. I want to use both onkeypress and onblur event. For that I wrote simple JavaScript program see here http://jsfiddle.net/wHgH5/29/.
I wanted to create jquery plugin so I can use in future easily with more friendly code.
On "return this each function" you can see I wrote keypress and blur function for that specific reason.
Problems which I am facing:
Firstly the blur event is not working so I can't trigger beforeBlurAction, afterBlurAction, onComplete functions and not to mention all the functionality in triggerBlurAction will not work.
Secondly even on keypress event it's assuming all "numberTextBox" input elements are same and doesn't apply separately. To understand it run the code snippet there are two input box with same classes, now type/press from keyboard "2.1.1" it will only allow "2.1" in that input box but on the second one it won't allow decimal. but if you empty first input box and it will allow writing single decimal on the second input box. I want to do it separately.
Check here https://jsfiddle.net/mzhe2rde/
//JQuery Custom Plugin inputNumericTextBox
(function($) {
jQuery.fn.inputNumericTextBox = function(options) {
var defaults = {
negativeAllow: true,
decimalAllow: true,
decimalError: false,
negativeSignError: false,
beforeKeypressAction: function() {},
afterKeypressAction: function() {},
beforeBlurAction: function() {},
afterBlurAction: function() {},
onError: function() {},
onComplete: function() {},
};
var settings = $.extend({}, defaults, options);
return this.each(function(i, element) {
$(document).on('keypress', element, function(e) {
triggerKeypressAction(e, element)
});
$(document).on('blur', element, function(e) {
alert(); //for testing but it's now working
triggerBlurAction(e, element)
});
});
function triggerKeypressAction(evt, element) {
settings.beforeKeypressAction.call(element, settings);
var regex;
var theEvent = evt || window.event;
var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
if (/\./.test(key) && /\./.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.decimalError = true;
settings.onError.call(element, settings);
return false;
}
/** Any idea on how to allow only one negative sign at the beginning?
write regex code here **/
if (settings.decimalAllow) {
regex = (settings.negativeAllow) ? /[0-9]|\-|\./ : /[0-9]|\./;
} else {
regex = (settings.negativeAllow) ? /[0-9]|\-/ : /[0-9]/;
}
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
settings.afterKeypressAction.call(element, settings);
}
function triggerBlurAction(evt, element) {
settings.beforeBlurAction.call(element, settings);
var inputValue = $(element).val(),
parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
if (isNaN(parsedValue)) {
$(element).val('');
} else if (settings.negativeAllow) {
$(element).val(parsedValue);
} else {
$(element).val(Math.abs(parsedValue));
}
settings.afterBlurAction.call(element, settings);
settings.onComplete.call(element, settings);
}
};
})(jQuery);
$(".numberTextBox").inputNumericTextBox({
negativeAllow: true,
decimalAllow: true,
beforeKeypressAction: function(e) {
console.log(this);
console.log(e);
console.log('before key');
},
afterKeypressAction: function(e) {
console.log(this);
console.log(e);
console.log('after key');
},
beforeBlurAction: function(e) {
console.log(this);
console.log(e);
console.log('before blur');
},
afterBlurAction: function(e) {
console.log(this);
console.log(e);
console.log('after blur');
},
onError: function(e) {
console.log(this);
console.log(e);
console.log('on error');
if (e.decimalError) {
alert('More than one decimal number is not allowed');
} else if (e.negativeSignError) {
alert('More than one negative sign is not allowed.\n You can only use negative at the start');
}
},
onComplete: function(e) {
console.log(this);
console.log(e);
console.log('on complete');
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="firstbox" type="text" class="numberTextBox" />
<input id="secondbox" type="text" class="numberTextBox" />
</body>
I thought I should try myself. what I did is put all the content of the plugin to another private function. and call the function in a loop to initialize every element separately. that way I achieved my goal and all events are working properly. and few more to support single negative sign. now it's proper input number textbox.
check it out here https://jsfiddle.net/mzhe2rde/6/
//JQuery Custom Plugin inputNumericTextBox
(function($) {
"use strict";
var inputNumericTextBox = function(element, options) {
var previous_value_set = false;
var previous_value = '';
var defaults = {
negativeAllow: true,
decimalAllow: true,
decimalError: false,
startNegativeSignError: false,
multipleNegativeSignError: false,
beforeKeypressAction: function() {},
afterKeypressAction: function() {},
beforeKeyupAction: function() {},
afterKeyupAction: function() {},
beforeBlurAction: function() {},
afterBlurAction: function() {},
onError: function() {},
onInitializationComplete: function() {},
};
var settings = $.extend({}, defaults, options);
$(element).on('keypress', function(e) {
//console.log("keypress");
triggerKeypressAction(e, element);
});
$(element).on('keyup', function(e) {
//console.log("keyup");
triggerKeyupAction(e, element);
});
$(element).on('blur', function(e) {
//console.log("blur");
triggerBlurAction(e, element);
});
settings.onInitializationComplete.call(element, settings);
function triggerKeypressAction(evt, element) {
settings.beforeKeypressAction.call(element, settings);
var regex;
var theEvent = evt || window.event;
var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
if (/\./.test(key) && /\./.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.decimalError = true;
settings.onError.call(element, settings);
settings.afterKeypressAction.call(element, settings);
settings.decimalError = false;
return false;
}
if (/-/.test(key) && /-/.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.multipleNegativeSignError = true;
settings.onError.call(element, settings);
settings.afterKeypressAction.call(element, settings);
settings.multipleNegativeSignError = false;
return false;
}
if (/-/.test(key)) {
previous_value_set = true;
previous_value = $(element).val();
}
if (settings.decimalAllow) {
regex = (settings.negativeAllow) ? /[0-9]|-|\./ : /[0-9]|\./;
} else {
regex = (settings.negativeAllow) ? /[0-9]|-/ : /[0-9]/;
}
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
settings.afterKeypressAction.call(element, settings);
}
function triggerKeyupAction(evt, element) {
settings.beforeKeyupAction.call(element, settings);
if (settings.negativeAllow && previous_value_set) {
if (!(/^-.*/.test($(element).val()))) {
$(element).val(previous_value);
settings.startNegativeSignError = true;
settings.onError.call(element, settings);
settings.startNegativeSignError = false;
}
}
previous_value_set = false;
previous_value = '';
settings.afterKeyupAction.call(element, settings);
}
function triggerBlurAction(evt, element) {
settings.beforeBlurAction.call(element, settings);
var inputValue = $(element).val(),
parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
if (isNaN(parsedValue)) {
$(element).val('');
} else if (settings.negativeAllow) {
$(element).val(parsedValue);
} else {
$(element).val(Math.abs(parsedValue));
}
settings.afterBlurAction.call(element, settings);
}
return;
};
if (!jQuery.fn.inputNumericTextBox) {
jQuery.fn.inputNumericTextBox = function(options) {
return this.each(function() {
inputNumericTextBox(this, options);
return this;
});
};
}
})(jQuery);
$(".numberTextBox").inputNumericTextBox({
negativeAllow: true,
decimalAllow: true,
beforeKeypressAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('before keypress');
},
afterKeypressAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('after keypress');
},
beforeKeyupAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('before keyup');
},
afterKeyupAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('after keyup');
},
beforeBlurAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('before blur');
},
afterBlurAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('after blur');
},
onError: function(e) {
//console.log(this);
//console.log(e);
//console.log('on error');
if (e.decimalError) {
alert('More than one decimal number is not allowed');
} else if (e.multipleNegativeSignError) {
alert('More than one negative sign is not allowed.');
} else if (e.startNegativeSignError) {
alert('You can only use one negative sign at the start');
}
},
onInitializationComplete: function(e) {
//console.log(this);
//console.log(e);
//console.log('on complete');
},
});
/* Last initialization settings will take the precedence but events will trigger on all initialization
* You shouldn't initialize more than one on a single element because it will create more object and it will take some memory to store it.
* It's their to support large environment */
/* This is an example of last initialization or initialization more than one */
/*
$(".numberTextBox").inputNumericTextBox();
var n = $(".numberTextBox").inputNumericTextBox({
negativeAllow: false,
decimalAllow: true
});
console.log(n);*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="text" class="numberTextBox" />
<input type="text" class="numberTextBox" />
</body>

Error: cannot call methods on tabs prior to initialization; attempted to call method 'destroy'

I'm working on updating an older site to the newer version of jQuery and applying bootstrap.
We are using
backbone.js
jQueryui and
bootstrap.js.
I am getting the following error: Error: cannot call methods on tabs prior to initialization; attempted to call method 'destroy'
The lines of code it is related to is:
Thanks
define([
'jquery',
'jqueryui',
'underscore',
'backbone',
'vm',
'events',
'models/product',
'text!templates/editor/page.html'
], function ($, jui, _, Backbone, Vm, Events, Product, PageTemplate) {
var EditorPage = Backbone.View.extend({
model: Product,
el: '#editor',
_$editorErrorContainer: undefined,
events: {
"click #toolbar": "onToolbarClicked"
},
initialize: function () {
this.bindSaveEvents();
Events.unbind("addText");//HACK: Prevents zombie listeners for this specific situation
Events.bind("addText", this.onAddText, this);
},
onAddText: function (e) {
var layers = this.model.get('layers');
var textCollections = [];
//Search for valid text collections in our layer and push into our array
layers.models.forEach(function (layer) {
var tc = layer.get("textCollection");
if (typeof tc !== "undefined") {
if (layer.get("allowText")) {
var printColor = layer.get("printColor");
var src;
if(printColor) { src = printColor.get("src"); }
var _tc = { 'textCollection': tc, 'src': src, 'name':layer.get('name'), 'cid': layer.cid };
textCollections.push(_tc);
}
}
});
//if there's no choice to make, just add the text element.
if (textCollections.length == 1) {
var textCollection = textCollections[0].textCollection;
AddTextToCollection(textCollection);
return;
}
//Otherwise create dialog for choosing in which text collection to put a new text object
var dialogHTML = "<div> <p>What color would you like this text?</p>";
//Generate selections, use the src attribute of the print color if it uses printcolor
//TODO use other attributes of a textCollection such as rgb color if it uses it etc
textCollections.forEach(function (textCollection, i) {
var imgurl = "";
if(textCollection.src) {
imgurl = "/productEditor/assets/printcolors/icons/" + textCollection.src;
}
//Customers wont like zero indexed option names
var id = i + 1;
dialogHTML += "<p data-id= " + i + " class='selection'> Group " + id + ": " + textCollection.name + "<img src='" + imgurl + "'/> </p>";
});
dialogHTML += "</div>"
$(dialogHTML).dialog({
modal: true,
width: "25%",
height: "auto",
dialogClass: "textAddDialog",
resizable: false,
position: {
my: 'left top',
at: 'left top',
of: $("#editor"),
collision: 'flip'
},
show: 'fade',
create: function() {
var that = this;
//bind dialog events
$(this).children(".selection").click(function(){
$(that).children('.selected').removeClass("selected");
$(this).addClass("selected");
});
},
open: function (event, ui) {
$('.ui-dialog').css('z-index',2003);
$('.ui-widget-overlay').css({
'z-index': 2002,
'opacity': 0.5
});
},
close: function() {
$(this).children(".selection").unbind();
$(this).dialog('destroy').remove();
},
buttons: [{
text: "Accept",
"class": "acceptButton",
click: function() {
var index = $(this).children('.selected').data('id');
if(index >= 0) {
var textCollection = textCollections[index].textCollection;
AddTextToCollection(textCollection);
}
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
function AddTextToCollection (textCollection) {
//Create text element in chosen group
var entry = textCollection.createEntry();
//Show user that this is a fresh text element that needs changing
entry.set("text", "Edit Me!");
entry.set("freshElement", true);//Fresh element denotes a completely new element, used to delete this element if user adds an element -> cancel button
//Trigger mouseup on element so our text editor dialog will pop for this element
var elem = $('.text_modifier[data-cid="' + entry.cid + '"]');
elem.trigger("click");
}
},
bindSaveEvents: function(){
Events.on('saveError', this.onSaveError.bind(this));
Events.on('saveSuccess', this.onSaveSuccess.bind(this));
},
unbindSaveEvents: function(){
Events.off('saveError', this.onSaveError.bind(this));
Events.off('saveSuccess', this.onSaveSuccess.bind(this));
},
onToolbarClicked: function (e) {
//console.log("toolbar clicked");
//this._productView.clearSelectedChildren();
},
onSaveError: function(errorMessage){
// if(this._$editorErrorContainer === undefined){
// this._$editorErrorContainer = $("<div/>").addClass("error");
// $(this.el).before(this._$editorErrorContainer);
// }
// this._$editorErrorContainer.text(errorMessage).show();
$('#appError').text(errorMessage).show();
},
onSaveSuccess: function(){
// if(this._$editorErrorContainer != null){
// this._$editorErrorContainer.hide();
// }
$('#appError').hide();
},
onRenderComplete: function (e) {
// ADD THE RETURN ELEMENT TO THE LIST OF
this._loadList = _.without(this._loadList, e);
if (this._loadList.length == 0) {
$(this.el).removeClass('loading');
}
},
remove: function(){
this.unbindSaveEvents();
},
renderApp: function () {
var that = this;
// PUT LIST OF ITEMS THAT RENDER INTO ARRAY
// renderComplete WILL REMOVE ITEMS, AND CHANGE STATE TO VISIBLE WHEN ALL ARE LOADED
this._loadList = ['layer', 'product', 'modifiers', 'tabs']
// CREATE PREVIEW MODIFIERS
require(['views/modifiers/product'], function (PreviewModifierView) {
that._modifierView = new PreviewModifierView({ model: that.model });
that._modifierView.on("renderComplete", that.onRenderComplete, that);
that._modifierView.render();
});
// CREATE PREVIEW
require(['views/preview/product'], function (PreviewProductView) {
that._productView = new PreviewProductView({ model: that.model });
that._productView.on("renderComplete", that.onRenderComplete, that);
that._productView.render();
});
// CREATE PRODUCT NAME DISPLAY
require(['views/toolbar/productname'], function (ProductNameView) {
that._productNameView = new ProductNameView({ model: that.model });
that._productNameView.render();
});
// CREATE PRODUCT DESCRIPTION DISPLAY
require(['views/toolbar/productdescription'], function (ProductDescView) {
that._productDescriptionView = new ProductDescView({ model: that.model });
that._productDescriptionView.render();
});
// CREATE TOOLBAR
require(['views/toolbar/layer'], function (ToolbarLayerView) {
that._toolbarView = new ToolbarLayerView({ model: that.model });
that._toolbarView.on("renderComplete", that.onRenderComplete, that);
that._toolbarView.render();
});
// CREATE FINISHED BUTTON
require(['views/toolbar/finished'], function (FinishedView) {
that._finishedView = new FinishedView({ model: that.model });
that._finishedView.render();
});
// CREATE TABS
require(['views/tabs/product'], function (TabsView) {
that._tabsView = new TabsView({ model: that.model });
that._tabsView.on("renderComplete", that.onRenderComplete, that);
that._tabsView.render();
});
},
render: function () {
//console.log("editor render!");
//console.log(this.model);
//$('#productName').html(this.model.get);
var pageTemplate = _.template(PageTemplate, this);
$(this.el).html(pageTemplate);
$('#button-editor-help').show(); // GET'S HIDDEN ON THE APPROVAL PAGE
this.renderApp();
}
});
return EditorPage;
});
In the tabs view, hook up a debugger where you call the destroy and create
Replicate the bug and check if you are calling destroy before initialization
May be you are calling close before the dialog is initialised.

knockout paging retaining old page on jquery dialog cancel and open

I have an issue with knockout paging .I am using knockout paging on jquery dialog.The issue is when i navigate from page1 to page2 ,page3 or page4 and close the dialog and open the dialog again i see the page which i closed last but not from first page .Attached the jsfiddle below.Please let me know if you have any questions.
http://jsfiddle.net/bharatgillala/yuvNt/57/
var data = [
{Player:"PAGE1", runs:"34889"},
{Player:"PAGE1", runs:"83366"},
{Player:"PAGE1", runs:"52534"},
{Player:"PAGE2", runs:"02232"},
{Player:"PAGE2", runs:"55899"},
{Player:"PAGE2", runs:"90483"},
{Player:"PAGE3", runs:"02565"},
{Player:"PAGE3", runs:"98500"},
{Player:"PAGE3", runs:"20285"},
{Player:"PAGE4", runs:"57757"},
];
var StaticDataExample1 = function(data){
// stuff I care about
this.items = ko.observableArray(data);
// pager related stuff
------------------------------
this.currentPage = ko.observable(1);
this.perPage = 3;
this.pagedItems = ko.computed(function(){
var pg = this.currentPage(),
start = this.perPage * (pg-1),
end = start + this.perPage;
return this.items().slice(start,end);
}, this);
this.nextPage = function(){
if(this.nextPageEnabled())
this.currentPage(this.currentPage()+1);
};
this.nextPageEnabled = ko.computed(function(){
return this.items().length > this.perPage * this.currentPage();
},this);
this.previousPage = function(){
if(this.previousPageEnabled())
this.currentPage(this.currentPage()-1);
};
this.previousPageEnabled = ko.computed(function(){
return this.currentPage() > 1;
},this);
};
ko.applyBindings(new StaticDataExample1(data),document.getElementById("test"));
$(document).on("click", "[id*=atest]", function ()
{
$("#test" ).dialog(
{
height: 420,
width: 430,
modal: true,
buttons: [
{
text: "Save",
},
{
text: "Cancel",
tabIndex: -1,
click: function () {
$(this).dialog("close");
}
}
],
close: function () { }
});
});
You're almost there actually.
Change your ko.applyBindings to this:
var model = new StaticDataExample1(data);
ko.applyBindings(model, document.getElementById("test"));
Then add an open: function to your $(...).dialog({ ... }) options right after the close: option:
close: function () {
},
open: function () {
model.currentPage(1);
}
Fiddle here: http://jsfiddle.net/yuvNt/63/
And it occurred to me just now; you could even just add the model.currentPage(1); call into your existing close: function if you don't want to add an open: function.
Hope that's useful.

How to recall a function with Jquery in this example?

How to recall a function and have the
dialog box keep coming back when click 'cancel' button with Jquery in this example?
I am sure it is easy but still learning some of the basics here.
Thanks
function definitelyClose() {
window.location = 'http://www.google.com'
};
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000;
var warnPeriod = 10000;
$(document).ready(function() {
$('#proba').dialog({
autoOpen: false
});
setTimeout(function() {
$('#proba').attr('title', 'Warning').text('Sesion will expire').dialog('open');
$('#proba').dialog({
buttons: {
'Cancel': function() {
$(this).dialog('close');
clearTimeout(autoCloseTimer);
}
}
});
autoCloseTimer = setTimeout('definitelyClose()', warnPeriod);
}, timePeriod);
});​
You need to create function with a name to
show the initial warning and
to call when the cancel button is clicked.
So you would get something like this:
$(document).ready(function() {
var autoCloseTimer;
var timePeriod = 5000;
var warnPeriod = 10000;
function definitelyClose() {
window.location = 'http://www.google.com'
};
// You need a function with a name
function showWarning() {
$('#proba').attr('title', 'Warning')
.text('Sesion will expire')
.dialog('open');
$('#proba').dialog({
buttons: {
'Cancel': function() {
$(this).dialog('close');
clearTimeout(autoCloseTimer);
// Now you can recall the function
setTimeout(showWarning, timePeriod);
}
}
});
autoCloseTimer = setTimeout(definitelyClose, warnPeriod);
}
$('#proba').dialog({ autoOpen: false });
setTimeout(showWarning, timePeriod);
});​

Categories

Resources