Just adding the bootstrap-confirmation extension for Bootstrap popover to some buttons on a project. I'm having issues with the options not being respected. I'm trying to get the popups to work as singletons and dismiss when the user clicks outside of them singleton and data-popout options, respectively - both set to true. I'm also not seeing any of my defined callback behavior happening.
I defined the options both in the HTML tags and in a function and neither works. Still getting multiple boxes and they don't dismiss as expected.
My JS is loaded after all other libraries and is in my custom.js file in my footer.
JS is as follows:
$(function() {
$('body').confirmation({
selector: '[data-toggle="confirmation"]',
singleton: true,
popout: true
});
$('.confirmation-callback').confirmation({
onConfirm: function() { alert('confirm') },
onCancel: function() { alert('cancel') }
});
});
An example of the box implemented on a button in my HTML is the following:
<a class="btn btn-danger" data-toggle="confirmation" data-singleton="true" data-popout="true"><em class="fa fa-trash"></em></a>
Any pointers would be appreciated. I even changed the default options in the bootstrap-confirmation.js file itself to what I want and still no luck.
Turns out I needed to rearrange a couple things to get this to work. I've left in the last_clicked_id etc stuff as I needed to add that to get the id value of what I'd just clicked.
// Product removal popup logic
var last_clicked_id = null;
var last_clicked_product = null;
$('.btn.btn-danger.btn-confirm').click(function () {
last_clicked_id = $(this).data("id");
last_clicked_product = $(this).data("product");
});
$('.btn.btn-danger.btn-confirm').confirmation({
singleton: true,
popout: true,
onConfirm: function () {
alert("DEBUG: Delete confirmed for id : " + last_clicked_product);
// TODO: Add AJAX to wipe entry and refresh page
},
onCancel: function () {
alert("DEBUG: Delete canceled for id : " + last_clicked_product);
}
});
I was a step ahead of myself with the callback logic which was not getting executed. Fixed by simply adding it to onConfirm: and onCancel: key values in the .confirmation() function. A bit of a RTFM moment there but this was unfortunately not very clear in the documentation.
Related
on didInsertElement i have initialised bootstrap popover and it works fine until i run an action i.e submit a form, after i save the form data on db i make a request to get the current saved data from api and then i use this.set() to update the model in realtime for the user... however after i use this.set() the popover breaks... to explain it a little better i'm gonna use an example below:
<form {{action 'saveForm' on='submit'}}>
{{input type="text" value=firstName class="form-control" placeholder="Firstname"}}
<button type="submit" class="btn btn-success" >Submit</button>
</form>
{{#each firstname in model.firstNames}}
<span data-toggle="popover" data-title="Firstname" data-content="{{unbound firstname}}" data-placement="top">Firstname</span>
{{/each}}
after using this.set() the popover inside #each doesn't work anymore..
UPDATE: this is the action where i call this.set()
App.firstNamesController = App.AppController.extend({
actions: {
updateFirstnames: function () {
$.getJSON('/api/firstnames/get/', function (jsonResponse) {
this.set('firstNames', jsonResponse.data.firstNames);
}.bind(this));
}
}
});
UPDATE #2:
App.firstNamesView = Ember.View.extend({
templateName: 'firstNamesTemplate',
didInsertElement: function() {
$('span[data-toggle="tooltip"]').tooltip({
trigger: 'click'
});
}
});
You'll need to (as Jeff mentioned) re-initialize your listeners after you set new names. didInsertElement isn't going to run every time new elements enter the DOM, it's just going to run when the view has been inserted for the first time once it's elements are ready.
Re-setting firstNames is adding new elements to the DOM after you set your listeners, so they aren't going to have the listeners set on them.
Untested solution:
App.firstNamesController = App.AppController.extend({
actions: {
updateFirstnames: function() {
$.getJSON('/api/firstnames/get/', function(jsonResponse) {
this.set('firstNames', jsonResponse.data.firstNames);
// add this after setting names:
Ember.run.next(this, function () {
$('span[data-toggle="tooltip"]').tooltip();
});
}.bind(this));
}
}
});
Also, your selector in your jQuery is targeting span[data-toggle="tooltip"] but your template has span[data-toggle="popover"] - is that a typo?
EDIT 1
Another option could be to observe the model.firstNames property and have the listeners get set any time model.firstNames changes. But observers can be a pain to manage.
// in your controller:
toolTipObserver: function () {
Ember.run.next(this, function () {
$('span[data-toggle="tooltip"]').tooltip();
});
}.observes('model.firstNames')
This question is an ongoing learning / discovery of these three questions. This issue for me started here:
First Post
Second Post
Now this post is regarding #StephenMuecke post about attaching the event handler dynamically. This was new to me so I had to read up but now I see that it does make sense.
Well after reading documentation and numerous SO posts I still can't seem to get the click event handler to fire??
This time I decided to take a different approach. I created a jsfiddle demonstrating the problem. http://jsfiddle.net/ramjet/93nqs040/17/
However the jsfiddle I had to change somewhat from reality to get it to work within their framework. Below is the actual code.
Parent Window script that launches modal...the alert Bound does fire.
<script>
$(document).ready(function ()
{
$("#new").click(function (e)
{
e.preventDefault();
var ischanging = false;
var financierid = 0;
var detailsWindow = $("#window").data("kendoWindow");
if (!detailsWindow)
{
// create a new window, if there is none on the page
detailsWindow = $("#window")
// set its content to 'loading...' until the partial is loaded
.html("Loading...")
.kendoWindow(
{
modal: true,
width: "800px",
height: "400px",
title: "#T("...")",
actions: ["Close"],
content:
{
url: "#Html.Raw(Url.Action("ActionName", "Controller"))",
data: { financierId: financierid, isChanging: ischanging }
}
})
.data("kendoWindow").bind('refresh', function (e)
{
alert('Bound');
$('document').on("click", "#save", function () { alert("i work");});
}).center();
}
detailsWindow.open();
});
</script>
The modal full html I didn't think was needed but if it is I will update it. This is just the element I am trying to dynamically bind to.
<input type="button" id="save" style="margin-right:10px;" value="Save Record" />
document doesn't need quotes:
$(document).on("click", "#save", function () { alert("i work");});
"document" searches for an element of document, not the actual document
$("document").length; //0
$(document).length; //1
I'm sure this is going to be simple well i hope it is. After racking my brain for days I have finally sorted my last problem thanks you someone on here, But now I have a new problem. I am dynamically creating blogs hundreds of them. I'm using JQuery to load a editor into a simple modal window like so
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
then the JQuery
jQuery(function($) {
var contact = {
message: null,
init: function() {
$('#edit').each(function() {
$(this).click(function(e) {
e.preventDefault();
// load the contact form using ajax
var blogid = $(this).data('id');
$.get("../_Includes/edit.php?blogid=" + blogid, function(data) {
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%", ],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
});
},
open: function(dialog) {
dialog.overlay.fadeIn(200, function() {
dialog.container.fadeIn(200, function() {
dialog.data.fadeIn(200, function() {
$('#contact-container').animate({
height: h
}, function() {
$('#contact-container form').fadeIn(200, function() {
});
});
});
});
});
},
show: function(dialog) {
//to be filled in later
},
close: function(dialog) {
dialog.overlay.fadeOut(200, function() {
$.modal.close();
});
},
};
contact.init();
});
the problem I have is i have hundreds of
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
but I want the all to run the same jQuery function above.
Can anyone help? Is there a simple way of doing this?
...many elements with same id...
That's the problem, you can't have multiple elements with the same id.
You probably want to use a class:
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
<!-- Added ---------^ -->
Then:
$('.edit').each(...);
// ^---- ., not #, for class
But you probably don't want to use each, just do:
$('.edit').click(function(e) {
// ...
});
There's no need to loop through them individually.
Another approach you might consider is rather than hooking click on each individual "edit" link, you might want to use event delegation. With that, you hook the event on an element that contains all of these "edit" links (there's bound to be a reasonable one, body is always possible as a last resort), but tell jQuery not to notify you of the event unless it passed through one of these on its way to that element in the bubbling. That looks like this:
$("selector for the container").on("click", ".edit", function(e) {
// ...
});
Within the handler, this will still be the "edit" link.
Use class instead of id as according to HTML standards each element should have a unique id.
id: This attribute assigns a name to an element. This name must be unique in a document.
class: This attribute assigns a class name or set of class names to an
element. Any number of elements may be assigned the same class name or
names. Multiple class names must be separated by white space
characters.
http://www.w3.org/TR/html401/struct/global.html
so use class instead of id
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
and refer to it with $('.edit')
I'm learning about Session and reactive data sources in Meteor JS. They work great for setting global UI states. However, I can't figure out how to scope them to a specific instance of a template.
Here's what I'm trying to do
I have multiple contenteditable elements on a page. Below each is an "Edit" button. When the user clicks on the Edit button, it should focus on the element and also show "Save" and "Cancel" buttons.
If the user clicks "Cancel", then any changes are eliminated, and the template instance should rerender with the original content.
Here's the code I have so far
// Helper
Template.form.helpers({
editState: function() {
return Session.get("editState");
}
});
// Rendered
Template.form.rendered = function(e){
var $this = $(this.firstNode);
var formField = this.find('.form-field');
if (Session.get("editState")) formField.focus();
};
// Event map
Template.form.events({
'click .edit-btn' : function (e, template) {
e.preventDefault();
Session.set("editState", "is-editing");
},
'click .cancel-btn' : function (e, template) {
e.preventDefault();
Session.set("editState", null);
},
});
// Template
<template name="form">
<div class="{{editState}}">
<p class="form-field" contenteditable>
{{descriptionText}}
</p>
</div>
Edit
Save
Cancel
</template>
// CSS
.edit-btn
.cancel-btn,
.save-btn {
display: inline-block;
}
.cancel-btn,
.save-btn {
display: none;
}
.is-editing .cancel-btn,
.is-editing .save-btn {
display: inline-block;
}
The problem
If I have more than one instance of the Form template, then .form-field gets focused for each one, instead of just the one being edited. How do I make so that only the one being edited gets focused?
You can render a template with data, which is basically just an object passed to it when inserted in to a page.
The data could simply be the key to use in the Session for editState.
eg, render the template with Template.form({editStateKey:'editState-topForm'})
you could make a handlebars helper eg,
Handlebars.registerHelper('formWithOptions',
function(editStateKey){
return Template.form({editStateKey:editStateKey})
});
then insert it in your template with
{{{formWithOptions 'editState-topForm'}}} (note the triple {, })
Next, change references from Session.x('editState') to Session.x(this.editStateKey)/ Session.x(this.data.editStateKey)
Template.form.helpers({
editState: function() {
return Session.get(this.editStateKey);
}
});
// Rendered
Template.form.rendered = function(e){
var $this = $(this.firstNode);
var formField = this.find('.form-field');
if (Session.get(this.data.editStateKey)) formField.focus();
};
// Event map
Template.form.events({
'click .edit-btn' : function (e, template) {
e.preventDefault();
Session.set(this.editStateKey, "is-editing");
},
'click .cancel-btn' : function (e, template) {
e.preventDefault();
Session.set(this.editStateKey, null);
},
});
Note: if you are using iron-router it has additional api's for passing data to templates.
Note2: In meteor 1.0 there is supposed to be better support for writing your own widgets. Which should allow better control over this sort of thing.
As a matter of policy I avoid Session in almost all cases. I feel their global scope leads to bad habits and lack of good discipline regarding separation-of-concerns as your application grows. Also because of their global scope, Session can lead to trouble when rendering multiple instances of a template. For those reasons I feel other approaches are more scalable.
Alternative approaches
1 addClass/removeClass
Instead of setting a state then reacting to it elsewhere, can you perform the needed action directly. Here classes display and hide blocks as needed:
'click .js-edit-action': function(event, t) {
var $this = $(event.currentTarget),
container = $this.parents('.phenom-comment');
// open and focus
container.addClass('editing');
container.find('textarea').focus();
},
'click .js-confirm-delete-action': function(event, t) {
CardComments.remove(this._id);
},
2 ReactiveVar scoped to template instance
if (Meteor.isClient) {
Template.hello.created = function () {
// counter starts at 0
this.counter = new ReactiveVar(0);
};
Template.hello.helpers({
counter: function () {
return Template.instance().counter.get();
}
});
Template.hello.events({
'click button': function (event, template) {
// increment the counter when button is clicked
template.counter.set(template.counter.get() + 1);
}
});
}
http://meteorcapture.com/a-look-at-local-template-state/
3 Iron-Router's state variables
Get
Router.route('/posts/:_id', {name: 'post'});
PostController = RouteController.extend({
action: function () {
// set the reactive state variable "postId" with a value
// of the id from our url
this.state.set('postId', this.params._id);
this.render();
}
});
Set
Template.Post.helpers({
postId: function () {
var controller = Iron.controller();
// reactively return the value of postId
return controller.state.get('postId');
}
});
https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#setting-reactive-state-variables
4 Collection data
Another approach is to simply state by updating data in your collection. Sometimes this makes perfect sense.
5 update the data context
Session is often the worse choice in my opinion. Also I don't personally use #3 as I feel like being less tied to iron-router is better incase we ever want to switch to another router package such as "Flow".
In our application we use a general function to create jQuery dialogs which contain module-specific content. The custom dialog consists of 3 buttons (Cancel, Save, Apply). Apply does the same as Save but also closes the dialog.
Many modules are still using a custom post instead of an ajax-post. For this reason I'm looking to overwrite/redefine the buttons which are on a specific dialog.
So far I've got the buttons, but I'm unable to do something with them. Is it possible to get the buttons from a dialog (yes, I know) but apply a different function to them?
My code so far:
function OverrideDialogButtonCallbacks(sDialogInstance) {
oButtons = $( '#dialog' ).dialog( 'option', 'buttons' );
console.log(oButtons); // logs the buttons correctly
if(sDialogInstance == 'TestInstance') {
oButtons.Save = function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
}
}
}
$('#dialog').dialog({
'buttons' : {
'Save' : {
id:"btn-save", // provide the id, if you want to apply a callback based on id selector
click: function() {
//
},
},
}
});
Did you try this? to override button's callback based on the need.
No need to re-assign at all. Try this.
function OverrideDialogButtonCallbacks(dialogSelector) {
var button = $(dialogSelector + " ~ .ui-dialog-buttonpane")
.find("button:contains('Save')");
button.unbind("click").on("click", function() {
alert("save overriden!");
});
}
Call it like OverrideDialogButtonCallbacks("#dialog");
Working fiddle: http://jsfiddle.net/codovations/yzfVT/
You can get the buttons using $(..).dialog('option', 'buttons'). This returns an array of objects that you can then rewire by searching through them and adjusting the click event:
// Rewire the callback for the first button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons[0].click = function() { alert('Click rewired!'); };
See this fiddle for an example: http://jsfiddle.net/z4TTH/2/
If necessary, you can check the text of the button using button[i].text.
UPDATE:
The buttons option can be one of two forms, one is an array as described above, the other is an object where each property is the name of the button. To rewire the click event in this instance it's necessary to update the buttons option in the dialog:
// Rewire the callback for the OK button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons.Ok = function() { alert('Click rewired!'); };
$('#dialog').dialog('option', 'buttons', buttons);
See this fiddle: http://jsfiddle.net/z4TTH/3/
Can you try binding your new function code with Click event of Save?
if(sDialogInstance == 'TestInstance') {
$('#'+savebtn_id).click(function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
});
}