How to create a ViewModel event pattern - javascript

I have a web application built using Knockout.js but the one thing I have failed to implement is proper reusable HTML. Right now even if I have a view such as a dialog which is shared by multiple other views I have to copy and paste the HTML code and nest it in the parent in order to achieve proper binding communication between the child and parent.
Here's an example:
<div class="person-view"> <!-- PersonViewModel -->
<div class="person-details">
<!-- Person details -->
</div>
<button type="button" data-bind="click: EditAddress">Edit address</button>
<div class="modal hide fade" role="dialog" data-bind="modal: ShowEditAddressModal, with: Address"> <!-- AddressViewModel -->
<div class="modal-header">
<h3>Edit address</h3>
</div>
<div class="modal-body">
<!-- Address details -->
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" data-dismiss="modal" data-bind="click: function() { $parent.SetAddress($data); }">Save</button>
</div>
</div>
</div>
In this case I have a sub-ViewModel which I am setting as the DataContext for the modal div. When the user clicks the Save button I am calling a method on the parent DataContext.
I know how to break the modal out to a separate HTML template and to generate the template dynamically supplying the ViewModel. That would work for showing and hiding the modal because I would simply need to do the following from within the code of the parent:
this.Address().IsShown(true);
In this case the modal would simply bind its visibility to a property on itself and the parent just needs to change it. That's fine.
However, what about when I click the Save button? I do not see how to have the parent respond to this occurrence using the MVVM pattern of Knockout.js. The button would still need a click binding which would bind to arbitrary code on the AddressViewModel, but how would it signal an event to its parent using Knockout?
Is there no way of doing this with Knockout and do I need to implement a separate library such as Underscore.js for events?

This is not a direct answer to your question, but the problem you're trying to solve is eliminated by using a library like DurandalJS which is built on top of knockout and handles view composition. There are a lot of features that Durandal provides to enable the kind of code reuse you're looking for, without having to reinvent the wheel. It's not the right fit for every project, but it might fit your needs.

Related

Google Analytics - Get nested span event click without class and id

I am using Tag manager and Anayltics 360.
My code as follows,
<div rel="ABC_Links" class="ak_widget" >
<!-- BEGIN: Widget - Links -->
<section class="mfb-30">
<div class="widget_links">
<div class="widget_container">
<div class="widget_content">
<button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">
<div class="widget_item">
<div class="widget_icon">
<svg>123</svg>
</div>
<div class="widget_text"><span style="overflow-wrap: normal;">ABCD TEXT</span></div>
</div>
</button>
<button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">
<div class="widget_item">
<div class="widget_icon">
<svg> 12345</svg>
</div>
<div class="widget_text"><span style="overflow-wrap: normal;">XYZ TEXT</span></div>
</div>
</button>
</div>
</div>
</div>
</section>
<!-- END: Widget Links --></div>
I have 12 buttons in this same format. Here i have given an example of two buttons.
Button name i can change later so i can not take it as hard coded for "Click Text" in tag manager.
I can use only rel= "ABC_Links" as unique identifier. I can not use any of below class as they are not unique.
I have used Custome javascript to get parent child relationship but didn't work.
I have used DOM element variable but it did not work.
Now Question is, Is there any way to trigger event in tag manager when i click on any of the button below and get the info in real time event in Anayltics 360 ???
One way to achieve this would be to create a User-Defined Custom JavaScript variable in GTM to set isABCLink=true on button click.
On the Variables screen under Built-In Variables make sure you have "Click Element" ticked.
Create a User-Defined Variable
Name: isABCLink
Type: Custom JavaScript
Code:
function() {
return {{Click Element}}.matches("div[rel=ABC_Links] button, div[rel=ABC_Links] button *");
}
Create a Trigger
Trigger Type: Click - All Elements
This trigger fires on: Some Clicks
Conditions: isABCLink equals true
Set up your tag firing on above trigger
Once caveat to point out is that the exact element clicked on could be the button or one of the child elements of the button such as the <svg> which might make it hard to set up your tag depending on what exactly you need.

How to toggle between two jQuery functions for Introjs tour plugin

I am in the process of learning jQuery and JS, so I apologize if this is a stupid, easy question.
I am working with a tour plugin called intro.js that adds hints to a web page (bootstrap page). I got the intro.js hints working, however I need to be able to show and hide all of the hints by toggling one button. The way the plugin currently works, you show the hints by clicking a button, then you have to manually click on each hint icon to view the tooltip, then click a button on the tooltip to hide the hint icon. The web pages could have several hints displayed (anywhere from 10-15) and users may not want to see what all hints are, as they may want to just see what 1 or 2 are then close all the hints - so I want to be able to toggle all of them on/off with one button.
According to the plugin API (view it here: https://introjs.com/docs/hints/api/), the hints are added when the button is clicked using this function: introJs.addHints(). You are supposed to be able to hide all of the hints using this function: introJs.hideHints().
So, how can I toggle both of these functions with one button?
Also, another issue I am having is if a user does not close all of the hint icons and they open a new page, the hint icons are still visible. If I refresh the page, they disappear. Related to this, if someone opens the hints and closes them, but decides to reopen the hints again, they do not open unless the page is refreshed. The API documentation has a function called: introJs.refresh() that says it refreshes and rearranges the hints. I think this is what I need to clear the existing hints (but I could be wrong). How can I clear/refresh the hints when the hints are closed so users can reopen the hints if needed, without refreshing - and so the hints disappear if a new page is opened and some hints were not closed.
Please help me with these questions and make a newbie's Christmas/holiday even better!!!
Here is a jsfiddle with hints added to a bootstrap modal. The Show Hints link is what I need to toggle on/off: http://jsfiddle.net/beaver71/fc0rkakn/
Thank you to everyone reading - and Happy Holidays to all of you.
Sample HTML:
<!-- Button trigger modal -->
Open Notes Modal
<!-- Modal -->
<div class="modal fade" id="notesModal" tabindex="-1" role="dialog" aria-labelledby="notesModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Notes</h4>
</div>
<div class="modal-body">
<div id="note-input" data-hint="Input your notes here." data-hintposition="top-middle" data-position="bottom-right-aligned">
<input type="text" name="note" class="col-md-11" maxlength="300"/><button id="add-note" data-hint="Select Add button to save and add your notes." data-hintposition="top-middle" data-position="bottom-right-aligned">Add</button>
</div>
</div>
<div id="note-total" data-hint="Track your remaining characters here." data-hintposition="top-middle" data-position="middle-right" style="margin-left:15px;">0/300
</div>
<div><a class="btn btn-tour" href="javascript:void(0);" onclick="javascript:introJs().addHints();"><i class="fa fa-bus"></i> Show Hints</a></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The API allows introJs to be commanded and for callbacks to be attached to various internal events, however it doesn't provide for inspection of state (in particular whether or not a hint is currently showing).
To achieve the toggle function, you will need to manage a state variable of your own.
Something like this ...
jQuery(function($) {
var hintShowing = false; // a variable by which to track the state of introJs.
introJs("#targetElment");
$("#myToggleButton").on('click', function() {
if(hintShowing) {
introJs.hideHints();
hintShowing = false;
} else {
introJs.showHints();
hintShowing = true;
}
});
function setShowing() {
hintShowing = true;
}
function resetShowing() {
hintShowing = false;
}
introJs.onchange(setShowing).oncomplete(resetShowing).onexit(resetShowing);
// add hints and set options here
});
That should work, at least to a certain extent. It depends on whether onchange fires when the initial hint is shown. If not, setShowing() will also need to be called manually (from your own code when the hint sequence starts) or maybe just initialise var hintShowing = true;

ui-sref open with new tab

I tried to open ui-sref in new tab, noted that i don't want to call it from controller. How to do from view end?
<div class="col-md-12 text-right wow fadeInUp">
<!-- submit button -->
<button ui-sref="app.blogs" target="_blank" class="btn btn-black " id="form-submit" type="submit" value="Submit">See all Blogs</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
</div>
If you want to open a ui-sref from the view you can use target="_blank", but note that the button element does not support target. Change your button into an anchor tag.
<a ui-sref="app.blogs" target="_blank">See all blogs</a>
If you want to continue to use the button element, I believe you need to use the controller.
adding logic to view is not a good practice, however,
you can add some function to your controller and use it in your view(in view you don't have access to WINDOW/DOCUMENT or any other variable/function which is not part of scope)
or you can use HTML tags same as #Zahid Rahman answer(like target="_blank")
but I really recommend you to use a controller for UI logic and services for general logics and API calls or sharing data between controllers

Pass data-attr in Materialize's modal (leanModal)

I am using Materialize framework in my rails app. I have this element that launch a modal on click:
<div data-target="modal1" class="modal-trigger" data-code="<%=code%>">lalala</div>
I want to catch the data-code in js and save it to variable. I've done something like this following the official documentation:
$('.modal-trigger').leanModal({
ready: function() {
var a = $(this).attr("data-code");
},
}
The variable "a" is undefined. How I can pass data-attr in Materialize modal? What is the best way? Thanks.
Update: I'd like to then display the value of data-code in the modal. This is the code:
<div id="modal1" class="modal bottom-sheet">
<div class="modal-content">
<p>The Code</p>
</div>
</div>
Update1: I eventually solved it with clickOn method and append the data attr to a particular div but wondering if it is possible to pass it also through modal.

Many different popups needed; Is it better to use one abstracted popup to handle every scenario

I have 3 different types of modal windows to handle different events. They popup to handle either:
1) Warnings, i.e. "hey, if you leave the page you will lose your work" kind of messages.
2) Dynamic data from a form the user previously filled out, i.e. "you are about to create a page with DataX: Data X, DataY: DataY, Date: March 28, 2012.
3) Form for the user to fill out.
I was originally trying to handle all 3 of the above scenarios with one set of html/css/javascript, just passing in data and modifying divs depending on situation. As I have expanded things, i'm noticing things being harder to maintain cleanly without being sloppy about it. I have a few questions which i'll list after I walk through how things are now.
Simplified HTML for modal popups:
<div id ="popup" style="display:none;">
<div class="modal-container">
<div class="modal">
<div class="modal-header">
<a class="close" href="# " title="Press Esc to close"><div id="close-label" title="Press Esc to close">Close</div></a>
<span id="top-header">WARNING</span>
</div>
<div class="modal-body">
<div class="modal-subhead">
<img class="subhead-icon" border="0" src="">
<span id= "header">WARNING</span>
</div>
<div class="modal-message"><span>If you leave this page, you will lose unsaved changed.</span></div>
<div class="modal-input-first">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-input-second">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-footer">
<a class="secondary" href="#">Cancel</a>
<span id = "button-secondary-label">or</span>
<span class="btn_container">
<span class="btn_left"></span>
<span class="btn_center">Continue</span>
<span class="btn_right"></span>
</span>
</div>
</div>
Right now this is located in a separate file with it's css and javascript and is loaded when the page is loaded.
In the main file I am changing the popup depending on what triggered the popup, just using jquery as such:
$('.modal-message').html('New Message');
$('.modal-subhead #header').text('New header');
The dynamic data is filled in similarly after first making the ajax request to get the data.
As I said, as things grow, i'm having to change a lot of this, and it's starting to feel sloppy. Especially as i'm having to make pixel perfect changes to the css for individual elements. Would it be best to have 3 completely separate sets of html to handle these? Where is the best place for this to live, is the separate file approach?
Is it better to keep adding separate elements as I need specific ones for certain instances, like so:
<div class="modal-input-specific-thing">
<div class="modal-label"></div>
<div id="modal-input"></div>
<div id="modal-input-2"></div>
</div>
Or to use jquery to change the structure of the html on the fly?
var new_input = 'modal-input' + count;
$('#modal-input').attr('id', new_input);
Is there a better method for pushing only the elements needed to a popup like this?
If I had 10-12 scenarios, which is possible as I keep expanding this. Is there a big enough performance hit to parsing 12 different sets of html/css every time page is loaded vs doing what i'm trying to do now...Making a generic/abstracted popup window, and push elements/data to it as the user needs?
Thanks!
I should do this with jQuery and jQuery UI. The jQuery UI has a real nice popup function called dialog. ( http://jqueryui.com/demos/dialog/ )
A working version that reconstruct your situation you will see here. ( http://jsfiddle.net/7GVmz/ )
There are a lot of options you can add so as buttons, callbacks on opening and closing. You can read all of it in the documentation on the jqueryui website ( http://jqueryui.com/demos/dialog/#option-disabled )
Html
<div id="popup-1" title="popup-1">
Hello World
</div>
<div id="popup-2" title="popup-2">
Hello World
</div>
<div id="popup-3" title="popup-3">
Hello World
</div>
JS
$(document).ready(function() {
$('#popup-1').dialog();
$('#popup-2').dialog();
$('#popup-3').dialog();
});​
Note
Its important that you load the jquery library and the jquery ui library.
​
I use SweetAlert for all my JavaScript alerts, it's a Better JavaScript Popup Box than the default and is really simple to use.
swal({<br>
title: "Are you sure you want to leave?",<br>
text: "You have unsaved changes!",<br>
type: "warning",<br>
showCancelButton: true,<br>
confirmButtonClass: "btn-danger",<br>
confirmButtonText: "Yes, Exit!",<br>
closeOnConfirm: false<br>
},<br>
function(){<br>
swal("Deleted!", "Your imaginary file has been deleted.", "success");<br>
});<br>
A full tutorial is here - https://kodesmart.com/kode/javascript-replacement-alert-box

Categories

Resources