GetUIKit3 - How to remove / add element to sortable? - getuikit

Two questions: I would like to add a "remove" link to a GetUIKit3 Sortable that will remove the element from the Sortable and call a server-side script to remove the element on the server.
In addition, how do I add an element to the end of an existing GetUIKit3 Sortable using JavaScript?

REMOVING
just add some button inside your sortable element and bind simple jquery on click event to it, something as simple as:
<ul uk-sortable>
<li data-db-id="nn"><img/><a class="del-button">Remove</a></li>
</ul>
$('.del-button').on('click', function(e){
e.preventDefault();
let $li = $(this).parent('li');
let myDbId = $li.data('db-id');
$li.remove();
$.ajax({
method: "POST",
url: "some.php",
data: { imgId: myDbId }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
})
If you want to make use of UIkit event - there's also a way to programatically catch remove event of the component, but I don't know if this method will return removed element from the args:
UIkit.util.on('ul[data-uk-sortable]', 'remove', function (el) {
console.log(el); //check if there's something
// do something, ajax probably
});
ADDING
$('ul[uk-sortable]').append('<li data-db-id="nn"><img/><a class="del-button">Remove</a></li>')
Of course you have to provide data that should be added to the container. Maybe you could combine dropzone event after upload(there should be something like that) and then append the result from that function.

Related

vue.js reference div id on v-on:click

Using v-on:click I'd like to set a variable with the id of the div in Vue.JS - how do I reference this?
<div id="foo" v-on:click="select">...</div>
<script>
new Vue({
el: '#app',
data: {
},
methods: {
select: function(){
divID = this.id // ??
alert(divID)
}
}
})
</script>
You can extend your event handler with the event object $event. That should fit your needs:
<div id="foo" v-on:click="select($event)">...</div>
The event is passed on in javascript:
export default {
methods: {
select: function(event) {
targetId = event.currentTarget.id;
console.log(targetId); // returns 'foo'
}
}
}
As mentioned in the comments, `$event` is not strictly necessary, when using it as the only parameter. It's a nice reminder that this property is passed on, when writing it explicitly.
However, nobody will stop you from writing the short notation:
<div id="foo" #click="select">...</div>
Beware that the method will not receive the `$event` object when you add another parameter. You need to explicitly add it at the position you will handle it in the listener. Any parameter order will work:
<div id="foo" #click="select(bar, $event)">...</div>
To find more options of the v-on directive, you can look through the corresponding entry in the vue documentation:
Vue API Documentation - v-on
Inspired by #nirazul's answer, to retrieve data attributes:
HTML:
<ul>
<li
v-for="style in styles"
:key="style.id"
#click="doFilter"
data-filter-section="data_1"
:data-filter-size="style.size"
>
{{style.name}}
</li>
</ul>
JS:
export default {
methods: {
doFilter(e) {
let curTarget = e.currentTarget;
let curTargetData = curTarget.dataset;
if (curTargetData) {
console.log("Section: " + curTargetData.filterSection);
console.log("Size: " + curTargetData.filterSize);
}
}
}
}
Just to highlight another option than the selected answer for the same question, I have a delete button on a record and want to perform an action with the record's unique id (a number). I could do the selected answer as before:
<button :id="record.id" #click="del">×</button>
This leaves the unfortunate reality that my del function needs to pull the id attribute out of the javascript event, which is more about the API (the DOM) than my domain (my app). Also using a number as an element id isn't ideal and could cause a conflict if I do it more than once in a view. So here's something that's just as clear and avoids any future confusion:
<button #click="()=>del(record.id)">×</button>
methods: {
del(id) {
fetch(`/api/item/${id}`, {method:"DELETE"})
}
}
You see, now my del function takes the record id instead of an event, simplifying things.
Note that if you do this wrong, you will invoke your delete function immediately, which is not what you want. Don't do this:~~
<button #click="del(record.id)">×</button>
If you end up doing that, Vue will call the del function every time this html fragment is rendered. Using the anonymous function ()=>del(record.id) will return a function that's ready to be executed when the click event happens.
Actually #nirazul proved this is fine. Not sure what my issue was.

Bootboxjs: how to render a Meteor template as dialog body

I have the following template:
<template name="modalTest">
{{session "modalTestNumber"}} <button id="modalTestIncrement">Increment</button>
</template>
That session helper simply is a go-between with the Session object. I have that modalTestNumber initialized to 0.
I want this template to be rendered, with all of it's reactivity, into a bootbox modal dialog. I have the following event handler declared for this template:
Template.modalTest.events({
'click #modalTestIncrement': function(e, t) {
console.log('click');
Session.set('modalTestNumber', Session.get('modalTestNumber') + 1);
}
});
Here are all of the things I have tried, and what they result in:
bootbox.dialog({
message: Template.modalTest()
});
This renders the template, which appears more or less like 0 Increment (in a button). However, when I change the Session variable from the console, it doesn't change, and the event handler isn't called when I click the button (the console.log doesn't even happen).
message: Meteor.render(Template.modalTest())
message: Meteor.render(function() { return Template.modalTest(); })
These both do exactly the same thing as the Template call by itself.
message: new Handlebars.SafeString(Template.modalTest())
This just renders the modal body as empty. The modal still pops up though.
message: Meteor.render(new Handlebars.SafeString(Template.modalTest()))
Exactly the same as the Template and pure Meteor.render calls; the template is there, but it has no reactivity or event response.
Is it maybe that I'm using this less packaging of bootstrap rather than a standard package?
How can I get this to render in appropriately reactive Meteor style?
Hacking into Bootbox?
I just tried hacked into the bootbox.js file itself to see if I could take over. I changed things so that at the bootbox.dialog({}) layer I would simply pass the name of the Template I wanted rendered:
// in bootbox.js::exports.dialog
console.log(options.message); // I'm passing the template name now, so this yields 'modalTest'
body.find(".bootbox-body").html(Meteor.render(Template[options.message]));
body.find(".bootbox-body").html(Meteor.render(function() { return Template[options.message](); }));
These two different versions (don't worry they're two different attempts, not at the same time) these both render the template non-reactively, just like they did before.
Will hacking into bootbox make any difference?
Thanks in advance!
I am giving an answer working with the current 0.9.3.1 version of Meteor.
If you want to render a template and keep reactivity, you have to :
Render template in a parent node
Have the parent already in the DOM
So this very short function is the answer to do that :
renderTmp = function (template, data) {
var node = document.createElement("div");
document.body.appendChild(node);
UI.renderWithData(template, data, node);
return node;
};
In your case, you would do :
bootbox.dialog({
message: renderTmp(Template.modalTest)
});
Answer for Meteor 1.0+:
Use Blaze.render or Blaze.renderWithData to render the template into the bootbox dialog after the bootbox dialog has been created.
function openMyDialog(fs){ // this can be tied to an event handler in another template
<! do some stuff here, like setting the data context !>
bootbox.dialog({
title: 'This will populate with content from the "myDialog" template',
message: "<div id='dialogNode'></div>",
buttons: {
do: {
label: "ok",
className: "btn btn-primary",
callback: function() {
<! take some actions !>
}
}
}
});
Blaze.render(Template.myDialog,$("#dialogNode")[0]);
};
This assumes you have a template defined:
<template name="myDialog">
Content for my dialog box
</template>
Template.myDialog is created for every template you're using.
$("#dialogNode")[0] selects the DOM node you setup in
message: "<div id='dialogNode'></div>"
Alternatively you can leave message blank and use $(".bootbox-body") to select the parent node.
As you can imagine, this also allows you to change the message section of a bootbox dialog dynamically.
Using the latest version of Meteor, here is a simple way to render a doc into a bootbox
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,MyCollection.findOne({_id}),box.find(".modal-body")[0]);
If you want the dialog to be reactive use
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,function() {return MyCollection.findOne({_id})},box.find(".modal-body")[0]);
In order to render Meteor templates programmatically while retaining their reactivity you'll want to use Meteor.render(). They address this issue in their docs under templates.
So for your handlers, etc. to work you'd use:
bootbox.dialog({
message: Meteor.render(function() { return Template.modalTest(); })
});
This was a major gotcha for me too!
I see that you were really close with the Meteor.render()'s. Let me know if it still doesn't work.
This works for Meteor 1.1.0.2
Assuming we have a template called changePassword that has two fields named oldPassword and newPassword, here's some code to pop up a dialog box using the template and then get the results.
bootbox.dialog({
title: 'Change Password',
message: '<span/>', // Message can't be empty, but we're going to replace the contents
buttons: {
success: {
label: 'Change',
className: 'btn-primary',
callback: function(event) {
var oldPassword = this.find('input[name=oldPassword]').val();
var newPassword = this.find('input[name=newPassword]').val();
console.log("Change password from " + oldPassword + " to " + newPassword);
return false; // Close the dialog
}
},
'Cancel': {
className: 'btn-default'
}
}
});
// .bootbox-body is the parent of the span, so we can replace the contents
// with our template
// Using UI.renderWithData means we can pass data in to the template too.
UI.insert(UI.renderWithData(Template.changePassword, {
name: "Harry"
}), $('.bootbox-body')[0]);

jquery accordion effect doesnt work when I use ajax

When I use ajax, I noticed that Jquery effects don't work. The reason is "The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time "
another similar question
Therefore, I changed my code to following but still I don't get the jquery effects.
Where I have done the mistake?
Previous code
$("#sendemp").click(function(e) {
e.preventDefault();
var submit_val = $("#searchbox").val();
//alert('submitval is ' + submit_val);
$.ajax( {
type : "POST",
//dataType :"jason",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_pimary_details',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion21').html(data);
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
});
New code
$("button").on( "click", "#accordion3",function(){
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_deatils_search',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
$("#accordion3").accordion({ heightStyle: "fill", active: 0 });
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
} );
I have following submit button
<input type="submit" id="sendemp" value="Search" />
I don't think your click binding is correct, if you want to handle clicks on button inside #accordion3 change it to:
$("#accordion3").on( "click", "button",function(){...});
It is hard to tell without your html, but it looks like in your old code you are replacing the sendemp button. In your new code your event delegation is incorrectly specified. You are applying delegation to a button element (which doens't exist since your sendemp button is an input element).
Apply delegate to something that is the parent of #sendemp like so:
$('body').on('click', '#sendemp', function() {
// your ajax call
});
I could fix the issue, I tried the above solution that is using on method. However, it doesn't make sense to my problem.
As following artical explain I think, Accordion is already instantiated and effects are persistance. When it is called second time, it won't create again since there is already the effects.
Therefore, I needed to destroy it and recreate accordion.
support link
I changed the code on success as follows
success : function(data) {
// alert('hhh');
$('#accordion3').accordion('destroy');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
//$("#accordion3").accordion( "disable" );
$("#accordion3").accordion({ active: 0 });
}
And out of $(document).ready(function() {
I added
$(function() {
$("#accordion3").accordion({
// heightStyle: "fill",
active: 0 });
});

Knockout 2 way foreach binding DOM changes update Model

If I have a list on a page, and it is using knockout's foreach binding to display list items, then something else updates the DOM to add an extra list item. If there any way I can get knockout to detect that DOM change and update its model to add the new item to the observableArray?
Here is a fiddle which shows the problem...
http://jsfiddle.net/BGdWN/1/
function MyViewModel() {
this.items = ko.observableArray([
{ name: 'Alpha' }, { name: 'Beta' }, { name: 'Gamma' }, { name: 'Delta' }
]);
this.simpleShuffle = function() {
this.items.sort(function() {
return Math.random() - 0.5; // Random order
});
};
this.simpleAdd = function() {
$("#top").append("<li>New item</li>");
}
}
ko.applyBindings(new MyViewModel());
It has 2 lists bound to the same observableArray, click the addItem button and you can see that the DOM is updated to include the new list item in the top list, but I would like the second list to be updated too, all via the model.
It seems that knockout ignores DOM elements that it didnt render, you can see this by clicking the shuffle button, it leaves the new items there. I would have expected it to remove them and do a full re-render.
Please don't answer with "Just add the item to the observableArray"
Take a look at the first link and the second link Interface MutationEvent
See Fiddle
$('#top').bind('DOMNodeInserted DOMNodeRemoved', function () {
alert('Changed');
});
I hope it helps.

jquery adding an onclick event to a href link

i am converting over from websforms to asp.net mvc and i have a question.
i have a loop that generates links dynamicallly where picNumberLink is a variable in a loop and image is a variable image link.
i want to avoid putting javascript actions inline so in my webforms project is did the following:
hyperLink.Attributes.Add("onclick", "javascript:void(viewer.show(" + picNumberlink + "))");
what is the equivalent using jquery in asp.net mvc?
I have seen examples of using the $(document).ready event to attach on clicks but i can't figure out the syntax to pass in the picNumberLink variable into the javascript function.
suggestions?
EDIT: If you generate your links with the ID of this form:
<a id="piclink_1" class="picLinks">...</a>
<a id="picLink_2" class="picLinks">...</a>
<script type="text/javascript">
$('a.picLinks').click(function () {
//split at the '_' and take the second offset
var picNumber = $(this).attr('id').split('_')[1];
viewer.show(picNumber);
});
</script>
var functionIWantToCall = function(){
var wrappedLink = $(this);
//some serious action
}
//this should be called on document ready
$("#myLinkId").click(functionIWantToCall);
If you need to get URL of picture, keep it in anchor`s href:
var functionIWantToCall = function(event){
event.preventDefault(); //this one is important
var link = $(this).attr('href');
//some serious action
}
$(document).ready(function()
{
$('#LinkID').click(function() {
viewer.show($(this).attr('picNumber'));
});
});
You can add an attribute called picNumber to your hyperlink tag and set this is your mvc view
The link in your view might look something like this:
<%= Html.ActionLink("Index", new { id = "LINKID", picNumber = 1 }) %>
Assuming you're able to change the HTML you output, can't you put the picNumberLink in the id or class attribute?
HTML:
<img src="..."/>
jQuery:
$(function() {
// using the id attribute:
$('.view').click(function() {
viewer.show(+/-(\d+)/.exec(this.id)[1]);
});
// or using the class attribute:
$('.view').click(function() {
viewer.show(+/(^|\s)foo-(\d+)(\s|$)/.exec(this.className)[2]);
});
}}

Resources