Using KnockoutJS with JQuery lightbox - javascript

I am making a KnockoutJS application where it should be possible to view products and when clicking them a detailed view of the selected product should be displayed to the user and an overlay should be put over the other products.
I have managed to get almost all of this working using JQuery and Featherlight.js. I am able to populate the detailed view with KnockoutJS observable variables but the problem I am having is that when the detailed view is displayed (using JQuery) the bindings to the KnockoutJS view model is lost. I want to be able to listen to click events using KnockoutJS (and call the function "update()" in the knockout controller shown in the code below) in the detailed view and update the view based on this event but as of right now this is only possible by using JQuery.
I think the problem is that when opening the detailed view using Featherlight.js a new "context" or instance is created that Knockout no longer have any bindings to. Anyone knows how this can be fixed?
Here is a fiddle: https://jsfiddle.net/d1txamd4/8/
Here is my code:
HTML
<div style="margin-top:2em;" class="row" data-bind="foreach: products">
<div class="col l4 m6 s12">
<div class="card">
<a href="#" data-bind="click: $parent.showProductDialog">
<div class="card-image">
<img data-bind="attr:{src: image}">
</div>
</a>
<div class="card-content">
<b data-bind="text: title"></b>
</div>
<div class="card-action">
<p style="float:left;"><span data-bind="text: price"></span> kr</p>
<a style="float:right;" class="btn disabled">Föreslå</a>
</div>
</div>
</div>
</div>
<!-- This is the HTML for the lightbox -->
<div class="lightbox">
<div class="lightbox-content">
<img data-bind="attr:{src: lightboxImage}"></br>
<b class="dialog-title" data-bind="text: lightboxTitle"></b>
<p data-bind="text: lightboxDescription"></p>
</div>
<div class="modal-footer">
<a data-bind="click: update" class="btn">Click me</a>
</div>
</div>
JavaScript
function ProductCardViewModel() {
var self = this;
// Array containing all products
self.products = ko.observableArray();
self.lightboxImage = ko.observable();
self.lightboxDescription = ko.observable();
self.lightboxTitle = ko.observable();
self.products = [
{"id":1,"name":"Cool healine","title":"It's cool to have a cool headline","description":"This text is suppost to describe something","price":700,"image":"http://www.swedishevent.se/se/wp-content/uploads/2010/11/takvandring_top.jpg","categories":[1,4]},{"id":2,"name":"Even cooler headline","title":"A nice headline is the key to success ","description":"What to write, what to write, what to write?","price":500,"image":"http://www.karlliesilva.com/Massage-Therapy-white-flower2.jpg","categories":[2]}
];
self.showProductDialog = function(product) {
self.lightboxImage(product.image);
self.lightboxDescription(product.description);
self.lightboxTitle(product.title);
$.featherlight('.lightbox');
};
<!-- I want to be able to call this function from the lightbox -->
self.update = function() {
alert("Success!");
};
}
ko.applyBindings(new ProductCardViewModel());

There are two issues here.
Issue one
The featherlight plugin appears to create new dom elements and then insert them into the dom. This means that knockout won't have anything bound to these injected elements.
Issue two
The submit binding only works within form elements, please see the knockout documentation
The solution
The solution is two use ko.applyBindings to bind your view model to the injected dom elements and change the submit binding to a click binding.
I have updated your fiddle with a working solution.

Check out the option persist introduced in version 1.3.0.
Instead of cloning your content, featherlight can instead "steal" it and persist it. This might be more appropriate to the way you bind your code.

Related

Javascript modal that displays list that closes and returns to main html

Rather new to javascript, jquery and bootstrap, etc., so bear with me. I have a situation where I want to present a list of errors in a model dialog after the user hits a "validate" button. Got all the working - I am generating a list of objects that indicate to the user they need more work to the exact spot that needs additional data entry. I have the the DIV "id" that represents the field that needs more data (and each item will jump someplace different).I do not want a drop down list since there are be lots and lots of these items.
A few questions:
How do I go about jumping from the modal to the main html. I believe I have seen scrollIntoView mentioned in a few other posts as I was looking but will that hop to the DIV and also close the modal?
What construct should I use for the list? A list of scrolling button? The size of this can be quite large (hundreds) so it will need a scroll capability.
Finally, the app is "paged" with a next and prev buttons. I assume that will not be a problem from the aspect of jumping to a page not already displayed?
Here is the current modal code:
<script id="template-validation-error" type="text/x-handlebars-template">
<div id="validationErrorModal" class="modal">
<div class="message-container">
<div class="header">
Validation Errors
</div>
<div class="message">
The following fields are required:
</div>
<div class="center">
<input type="button" class="btn btn-solid-green btn-sm" onclick="fffdevice.validationErrorOk();" value="Done" />
</div>
</div>
</div>
</script>
and
showValidationError: function (fieldlist) {
settings.focusedField = $(':focus');
$("#validationErrorModal").detach();
$(".device-container").append(templates.validationerror({ fieldlist }));
$(".message-container input").focus();
},
validationErrorOk: function () {
$("#validationErrorModal").detach();
if (settings.focusedField) {
settings.focusedField.focus();
}
},
The field list is a list of objects that contain the id (field.id) of the DIV and also a description (field.fieldName) that I want to display.
Here is something I mocked up in paint...I am not sold on it but it show in a general sense what I am looking for:
I don't need a full solution rather, just want mechanisms I can use.
UPDATE
Just to help out anyone else in the future, using the info provided in the correct answer below I have a new code as follows:
<script id="template-validation-error" type="text/x-handlebars-template">
<div id="validationErrorModal" class="modal">
<div class="validation-container">
<div class="header" align="center">
Validation Errors
</div>
<div class="message">
<div class="scrolling-container" style="background-color: rgb(238, 238, 238); height:660px">
<div class="grid grid-pad">
{{#each fieldlist}}
<div class="row click-row" onclick="fffdevice.validationErrorFix('{{id}}');">
<div class="col-7-8 field-name">{{fieldName}}</div>
<div class="col-1-8">
<img class="pull-right" src="/mysite/Content/device/images/fix.png" style="width: 40px; position:relative; top: -5px;">
</div>
</div>
{{/each}}
</div>
</div>
</div>
<div><br/></div>
<div class="center">
<input type="button" class="btn btn-solid-green btn-sm" onclick="fffdevice.validationErrorOk();" value="Done" />
</div>
</div>
</div>
Then the Javascript for the onClick is:
validationErrorFix: function (id) {
$("#validationErrorModal").detach();
var x = document.getElementById(id);
x.scrollIntoView({
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
},
Which closes the dialog and jumps to the field. It looks like (I know this is ugly and I will clean it up later):
Bind the modal event to the validation code and show the modal if error(s) are found.
Display the modal with the list of errors using an html unordered list, inside the li element an anchor tag where the href attribute will have a value with the id that corresponds to the input field, all this done dynamically from your validation code.
Once an error in the list is clicked hide the modal using bootstrap $('#your-error-modal').modal('hide'); so the code would be something like this:
$('#your-error-modal').on('click', 'a.error-item', function(){
$('#your-error-modal').modal('hide');
});
I haven't tested this code, but if you're having issues with scrolling to the section of the input and closing the modal you can probably do something like this too:
$('#your-error-modal').on('click', 'a.error-item', function(e){ // use this method of onclick because your list will be created dynamically
e.preventDefault(); // prevent the default anchor tag action
var href = $(this).attr('href'); // grab the href value
$('#your-error-modal').modal('hide'); // close the modal first
scrollToDiv(href); // then take the user to the div with error with a nice smooth scroll animation
});
function scrollToDiv(location) {
$('html, body').animate({
scrollTop: $(location).offset().top
}, 2000);
}
Again this is untested code, but the idea is there.
For UX reasons you might also want to create a floating div or something where users can click on it and go back to the modal to continue reading your list of errors.

CSS Animation not firing with Knockout code on click of a button - and not dispatching click event

I'm running into an issue with some Knockout code firing off a CSS3 animation. It works with one block of code, and doesn't on another. The idea is to show an animation when you add an item to the cart. The object in the code not working is coming up empty, where as the one working displays the product notification' div. The other issue is that $('#cart-nav a.first').click(); is not getting dispatched when this action is performed. This is not working in either scenario.
Below is where the code works (for the animation), and another where it does not. Appreciate any help. Thanks
Working code where CSS3 Animation fires off when you add an item to the cart. The class 'rise' triggers the animation. One working block of code, the other not working, and the JS below that. Thank you
Works
<div class="thumbnail product-image medium">
<div class="actions">
<div class="product-notification-cont">
<div class="product-notification"> Added to cart!</div>
</div>
Add to Cart
More Info
</div>
<a href="" data-bind="attr:{href:'/#products/'+$data.id}">
<img src="" data-bind="attr:{alt:$data.name, src:$root.servicePath+'products/'+$data.id+'/images/preview_image/medium?auth='+ax.JRR}" />
</a>
</div>
Doesn't work
<div class="product-info" data-bind="visible:!(productLoading())">
<h2 data-bind="text:product().name"></h2>
<div class="product-description" data-bind="html:product().description">
</div>
<div class="product-notification-cont">
<div class="product-notification"> Added to cart! </div>
</div>
<button class="button" data-bind="click:addProductToCart.bind($data,productMoreInfo())">Add to Cart</button>
<? } else { ?>
<h3><?=l(23)?></h3>
<? } ?>
</div>
JS (console.log in there for debugging purposes)
self.addProductToCart = function(data, event) {
var $productNotification = $(event.target).prev().children('.product-notification');
console.log($productNotification);
ax.Cart.addCartItem({product_id:data.id, name:data.name, description:data.description});
$('#cart-nav a.first').click();
$productNotification.addClass('rise');
$productNotification.on('animationend',function() {
$(this).removeClass('rise');
});
};
The main difference I spot is this:
The working data-bind binds $data as this:
data-bind="click:$root.addProductToCart.bind($data)"
The not-working data-bind binds $data and the first argument of addProductToCart:
data-bind="click:addProductToCart.bind($data,productMoreInfo())"
Knockout's default click handler signature is:
function(data, event) { }
which matches your addProductToCart signature. The second (faulty) data-bind creates these parameters:
productMoreInfo(), $data, clickEvent
I.e.: it adds the additional parameters in bind to the front of the arguments list.
The quick solution would be to create a new event listener that handles the extra parameters. However, I'd strongly suggest changing your approach altogether. You should look in to afterRender, the css binding and custom bindings. Avoid DOM related jQuery code in your view models.

Dynamically create page in jquery mobile, only to include specific data from websql database

I have an application that has a page where all id's are selected from the table and specific bits of information are shown in html.
What i would like to do next is to make each of these elements as a whole a link to essentially, a 2nd level down.
This level down page will reveal all information bound to that row's id, is it possible to build this in a way that is dynamic?
I am using jQuery mobile to build pages, and i'd like to use 1 template and append the relevant html elements into it, and populate each with the id bound information.
I hope this makes some sense, and any guidance or suggestions would be greatly appreciated.
The above mockups represent what i would like to achieve, the left image displays a list of all rows in the table, upon clicking one of them, you are taken to another page, with only information for that particular id.
Can i achieve this for each item within the list?
It's a good navigation example and it's not difficult to implement.
Since the information is coherent (every DB row has the same columns), create just one empty template (edit: it's now based on your PasteBin):
<div data-role="page" id="route_details">
<div data-role="header">
<a data-rel="back"><i class="fa fa-arrow-left"></i></a>
<h1 id="walkTitle"></h1>
</div>
<div data-role="main" class="ui-content">
<div class="finishedRouteInfo">
<div class="mapDetails" style="width: 100%; height: 150px;"></div>
<div class="ui-grid-a">
<div class="ui-block-a home_btns no_border">
<div class="ui-block-a finishedDistance"><i class="fa fa-map-marker"></i></div>
<div class="ui-block-b"><p>Distance <br/><span id="finalDistance" class="value"></span></p></div>
</div>
<div class="ui-block-b home_btns">
<div class="ui-block-a finishedDistance"><i class="fa fa-clock-o"></i></div>
<div class="ui-block-b finishedDuration"><p>Duration <br/><span class="value" id="finalDuration"></span></p></div>
</div>
<span class="horizontalSplitter"></span>
<div class="walkDescription"></div>
</div>
</div>
</div>
The code in your PasteBin cannot work because you are creating multiple pages with elements having the same IDs (i.e.: finalDistance, finalDuration). Also, you are creating many pages which probably the user will never see.
So, simplify your loading function:
var last_results = [];
$(document).on("pageinit", "#my-routes", function() {
db.transaction(function(t){
t.executeSql('SELECT * FROM WALKS', [], querySuccess, errorCB);
});
function querySuccess(t, results, Element) {
last_results = results;
}
});
and delay the content/map creation just before showing the page with route details:
$("#route_details").on("pagecontainerbeforeshow", function()
{
// use your DB data
var data = last_results.rows.item(clicked_route);
$("#walkTitle).html(data.WalkTitle);
$(".walkDescription").html(data.WalkDescription);
// ...create the map and fill the rest...
});
You just have to link each route to this page, setting clicked_route when the link is clicked using something like this:
<a class="walkPage" href="#route_details" data-route="0">Route 0</a>
<a class="walkPage" href="#route_details" data-route="1">Route 1</a>
<a class="walkPage" href="#route_details" data-route="2">Route 2</a>
JavaScript:
$(document).on("click", ".walkPage") {
clicked_route = parseInt($(this).attr("data-route"));
});
...Since you have to show the route map in two different pages, refactor your code so that you can easily create a map and add it to any page.
Hope it's sufficiently clear to fully implement it.

Displaying JavaScript Hidden Elements in Other Location on Page

Update: I have changed my JavaScript code, and I am now receiving errors in my iPhone Debug Console.
Disclaimer: I'm new to web development, and I'm not too good with JavaScript.
Scenario: I'm building an event calendar with CodeIgniter, and I'm hiding elements on mobile devices that need to be displayed elsewhere on the page when an event occurs. The elements being hidden are <ul>s, and they need to be displayed on another portion of the page when their cooresponding <span>s with the class .day_listing_mobile are selected. I've been working with different methods, but I haven't been able to find a solution out for hours as I'm not strong in the realm of jQuery/Ajax/JavaScript.
Question: What methods would be required to make the hidden <ul>s be displayed on a different portion of the page when their corresponding <span>s are selected?
JavaScript (Updated):
(function($) {
var isMobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (isMobile) {
$('.event_list').hide(); // setting display:none; on all .event_list <ul> elements
// attach click event to the <span class="day_listing"> elements
$('.day_listing_mobile').click(function() {
var eventList = $(this).sibling('.event_list').clone();
$(this).sibling('.event_list').remove();
$('#mobile_show_content').append(eventList);
});
}
})(jQuery);
I'm Receiving this error on this line of code var $eventList = $(this).sibling('.event_list').clone(); :
CodeIgniter Calendar Template (Controller):
{cal_cell_content}
<span class="day_listing_mobile">
{day}
</span>
<ul class="event_list">
{content}
</ul>
{/cal_cell_content}
{cal_cell_content_today}
<span class="day_listing_mobile" id="today_listing">
{day}
</span>
<ul class="event_list">
{content}
</ul>
{/cal_cell_content_today}
View:
<div class="row">
<div class="twelve columns">
<?php echo $calendar; ?>
</div>
</div>
<div class="show-on-phones">
<div class="row">
<div class="twelve columns" id="mobile_show_content">
<!--I want the <ul>s to show up here-->
</div>
</div>
</div>
Note that the CodeIgniter calendar class generates above where I want to display the <ul>s.
Just modify your click event to move the data around the dom.
$('.day_listing_mobile').click(function() {
var eventList = $(this).sibling('.event_list').clone();
$(this).sibling('.event_list').remove();
$('.mobile_show_content').append(eventList);
});
You can remove the node from the DOM and re-append it in a different place. (.remove() and .append())
But, rather than trying to solve this in javascript, why not design your page with adaptability in mind using css selectors to reflow the page at certain view port widths.
Check this out:
http://www.alistapart.com/articles/responsive-web-design/

How can i update the underlying data in colorbox?

I am trying to combine knockout.js and colorbox in a photo-gallery.
I have all photos in an observable array, and the code looks something like this:
<script type='text/javascript>
function Photo(src, comment) {
this.image = src;
this.comment = ko.observable(comment);
}
var view_model = {
photos: ko.observableArray([
new Photo('/gallery/img1.jpg', 'Some comment'),
new Photo('/gallery/img2.jpg', 'Some other comment'),
new Photo('/gallery/img3.jpg', '')
]),
current_photo: ko.observable()
};
$(document).ready(function(){
$('ul#gallery').colorbox({href: '#photo-detail'});
});
</script>
<script id='photoTemplate' type='text/html'>
<li>
<img src='{{src}}' />
<div>{{comment}}</div>
</li>
</script>
<body>
<ul id='gallery' data-bind='template: "photoTemplate, foreach:photos"'</ul>
<div style='display: none'>
<div id='photo-detail'>
<img data-bind='attr: { src: current_photo().src }'/>
<input type="text" data-bind='value: current_photo().comment'/>
</div>
</div>
</body>
I update current_photo in the event-handler for colorbox, when a new image loaded. Everything works until i edit a comment.
It seems like knockout removes the DOM-element, and replaces it with a new, so when moving to next photo and then back again, colorbox bugs out. If i close colorbox and reinitialize, it works again.
Is there a way to update the the data for colorbox, without closing it?
I think instead of using the jquery template, just use Knockout 1.3 and the new foreach binding:
http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/
<ul data-bind="foreach: products">
<li>
<strong data-bind="text: name"></strong>
<em data-bind="if: manufacturer">
— made by <span data-bind="text: manufacturer.company"></span>
</em>
</li>
</ul>
It basically just duplicates the nodes underneath the parent, so you don't need to use the templating unless its much more complicated.
You are correct that the jquery template implementation you are using recreates the nodes which probably kills the colorbox, I think the new foreach implementation should leave the nodes in place and work better.
If that fails though you may have to write your own custom knockout binding or something to bind a list to colorbox.

Categories

Resources