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.
Related
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.
I'm using RequireJS to structure my JS which is why I'm using a $.proxy function. What I'm trying to do within the .each function is give each carousel on the page a unique data attribute. In order to do this I have to be able to target each carousel, but $(this) in this context doesn't target each carousel. I've tried using currentTarget but I think this only works on click events?
Below is the specific snippet which needs fixing.
getCarousels: function() {
$carousel.each($.proxy(function(index) {
$owl = (index.currentTarget);
$owl.attr('data-number', index);
this.initCarousel();
},this));
},
And here is the full file.
define(['owlcarousel'], function() {
var $ = jQuery,
$carousel = $('.carousel'),
$data = $('.carousel-data');
function updateResult(pos, value, carouselNumber) {
$(carouselNumber).find(pos).text(value);
}
function afterAction(el) {
var owl = el.data('owlCarousel'),
actualValue = this.owl.currentItem + 1,
carouselNumber = el.attr('data-number');
console.log(carouselNumber);
updateResult('.carousel-current', actualValue, carouselNumber);
updateResult('.carousel-items', this.owl.owlItems.length, carouselNumber);
}
return {
init: function() {
if($carousel.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.getCarousels();
},
getCarousels: function() {
$carousel.each($.proxy(function(index) {
$owl = (index.currentTarget);
$owl.attr('data-number', index);
this.initCarousel();
},this));
},
initCarousel: function() {
$carousel.owlCarousel({
singleItem: true,
autoPlay: true,
slideSpeed: 400,
paginationSpeed: 800,
lazyLoad: true,
afterAction: afterAction
});
}
};
});
.each receive 2 parameters which is the index and the value. Usualy the value is the same as this, but well, you overrided it. Get that second parameter! :
$carousel.each($.proxy(function(index, el) {
$owl = $(el);
$owl.attr('data-number', index);
this.initCarousel();
},this));
But why not simply not use proxy?
var that = this
$carousel.each(function(index) {
$owl = $(this);
$owl.attr('data-number', index);
that.initCarousel();
});
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
Here's the JS i have:
jQuery(function ($) {
var OSX = {
container: null,
init: function () {
$("input.osx, a.osx").click(function (e) {
e.preventDefault();
$("#osx-modal-content").modal({
overlayId: 'osx-overlay',
containerId: 'osx-container',
closeHTML: null,
minHeight: 80,
opacity: 65,
position: ['0',],
overlayClose: true,
onOpen: OSX.open,
onClose: OSX.close
});
});
},
open: function (d) {
var self = this;
self.container = d.container[0];
d.overlay.fadeIn('slow', function () {
$("#osx-modal-content", self.container).show();
var title = $("#osx-modal-title", self.container);
title.show();
d.container.slideDown('slow', function () {
setTimeout(function () {
var h = $("#osx-modal-data", self.container).height()
+ title.height()
+ 20; // padding
d.container.animate(
{height: h},
200,
function () {
$("div.close", self.container).show();
$("#osx-modal-data", self.container).show();
}
);
}, 300);
});
})
},
close: function (d) {
var self = this; // this = SimpleModal object
d.container.animate(
{top:"-" + (d.container.height() + 20)},
500,
function () {
self.close(); // or $.modal.close();
}
);
}
};
OSX.init();
});
I'm using this lightbox script for survey and the html includes form,
and this code make the lightbox open by clicking on button, all i need is to use the same lightbox and make it automatically open upon opening the page.
Thanks in advance
You can just trigger click() programatically on a button that shows the popup after page loads.
Example:
$(function () {
$('your_button').click();
})
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);
});