Update element's text when $emit function has been triggered - javascript

In vue, would it be possible to update element text when $emit function has been triggered inside the element?
Here is a code snippet:
<a href="#" #click="fire('openCrudRoleModal',{{$role}})"
#updateRoleName="change text in this <a>">{{$role->name}}</a>
Within Laravel blade loop, I am generating links. Inside link I got vue click event, when clicked, it opens a modal with form.
After I update record (with ajax), I am triggering this.$emit('updateRoleName',response.name);
It would be nice if I could update the link text, which was clicked, without any additional vm methods.
Any thoughts..., can this be done?

Fallowing suggestions, I stopped at this solution. Not the best, but kind of works.
So in Laravel blade I am generating link, here I can also do the roles/permission check:
<th>
#can('edit role') <role-name-link :role="{{$role}}" /> #endcan
</th>
Inside <role-name-link />
<template>
{{name}}
</template>
<script>
export default {
props: ['role'],
name: "RoleNameLink",
data() {
return {
name: this.role.name
}
},
methods: {
open(){
Event.fire('openCrudRoleModal',this.role);
},
updateName(e){
this.name = e.name;
}
},
created() {
Event.listen('updateRoleName', (role) =>{
if(this.role.id == role.id) this.name = role.name;
});
}
}
</script>
Once link is clicked on, it will open a modal with update form. After update is completed it will $emit (Event.fire()) another event to update link text.
onSubmit(){
this.spinner = this.form.processing;
this.form[this.action]('/admin/roles/')
.then(response => {
this.$toastr.s('Role '+this.actionName[this.action]);
if(this.action == 'patch') Event.fire('updateRoleName',response);
this.hide();
});
}
Back inside <role-name-link />, I still need to compare id's if(this.role.id == role.id) this.name = role.name;, else it will update all names in the table.
This will update the name in the php generated table. One gotcha there is, if I click the same link again, inside form it will show me the original name that was echoed by php.
Any thoughts, suggestions. How to make it better.... more elegant?

Related

How to add a custom plugin in TinyMCE React for form elements with actions?

I would like to create a form with some buttons,checkbox and other form elements. When the button is clicked some action need to happen.
I tried to add actions in this way,
function handleChange(){
alert("Ok")
}
function checkBox() {
return '<input type="checkbox" onchange='+ handleChange() + '> Hello </input>';
}
editor.ui.registry.addMenuItem("checkbox", {
text: 'checkBox',
onAction: function () {
let html = checkBox();
editor.insertContent(html);
}
})
})```
In such cases the action is called before and not at the onChange of the element. How to achieve this and have control over the element inside the tinyMCE React editor.

How to recognize which button is clicked

I am using wordpress for my blog posts - all posts are fetched on the same page and each post has button, I need to be able to recognise which button of which post was clicked.
I can do it only with hardcoded data, but I am unsuccessful with dynamic ones.
I tried to give a trigger button common class and then detect it in JS.
<div class="row">
<button class="common-button-class">CLICK</button>
</div>
let openButton = document.getElementsByClassName(
'common-button-class'
);
if (openButton != null) {
document.querySelector('.common-button-class')
.addEventListener('click', (event) => {
// tried detect event id here unsuccessfully
});
}
Is there function of how to know which post is being triggered?
Use querySelector instaid of getElementsByClassName
let openButton = document.querySelector('.common-button-class');
openButton.onclick = function() {
//Your code here
};
you can use jquery in WordPress
first add properties just like data-id and keep post id in it.
then :
$(document).on("click",".common-button-class", function () {
var clickedBtnID = $(this).data('id');
alert('you clicked on button #' + clickedBtnID);
});

Manipulating dom elements dynamically in react?

I am trying to have a button change color when the user clicks it in React. Each button I am trying to add this functionality to is also updating state. How can I interact with styles AND update state when these buttons are clicked? Here's my crude attempt:
Some HTML:
<div className="searchPrivacyContainer">
<p>USERS CAN SEARCH FOR MY PROJECT:</p>
<div className="searchPrivacySelect">
<div
className="searchPrivacyYes"
onClick={
(holdColor,
function () {
setProposal({ ...proposal, searchable: true });
})
}
>
And this is the most basic version of the function I'm trying to bind. Writing the body of the function should be the straightforward part hopefully, I just don't know how to bind it to the div which is already calling another function:
const holdColor = (event) => {
console.log(event.target.style);
};
I think this part isn't not working as you expecting,
onClick = {
(holdColor,
function() {
setProposal({ ...proposal,
searchable: true
});
})
}
Simple test,
function x(ev){console.log('x', ev)}
function y(ev){console.log('y', ev)}
const listener = (x, y)
listener(123)
Look, first one (x) never got called, So, you might wanna do something like this on your listener.
onClick={(ev) => {
holdColor(ev)
setProposal({ ...proposal,
searchable: true
});
}}
EDIT:
see this working example (it might be helpful), https://codesandbox.io/s/eloquent-wilson-drbbk?fontsize=14&hidenavigation=1&theme=dark

Jquery Select Dynamically added element

Several similar question exist, but after fighting with this for a day or so I feel the need to ask because the vast majority of the answers refer to adding event handlers to elements.
I am not interested in adding an event handler to the elements in question, rather I am interested in adding additional dynamic content to dynamically generated content.
The app works thusly:
load a modal form dynamically upon the click of a static element (working properly)
function loadModal(target,modalId) {
console.log("==================> loadModal() Entry");
$.ajax({
type: "GET",
url: 'http://localhost/retrieve-modal/'+modalId,
success : function (text) {
$("#"+modalId)[0].innerHTML = text;
modalSaveIntercept($("#"+modalId)[0])
},
failure : function (e) {
console.log("something is wrong");
}
})
}
Then I have a save interceptor that overrides the default save behavior of my form here this is also working properly, (I suspect because I am loading this event handler at the time of loading the modal)
function modalSaveIntercept(eventTarget) {
if(eventTarget.hasChildNodes()) {
eventTarget.childNodes.forEach(function(e) {
if(e.tagName == "FORM") {
console.log("found the form: " + e.id + " applying save override listener");
$("#"+e.id).submit(function(event){
event.preventDefault();
submitForm(e);
});
modalSaveIntercept(e)
}
});
}
}
the above attaches a listener to the form loaded into my modal and rather than firing the default behavior of a Save button click, it fires my submitForm() function which is here:
function submitForm(form) {
let payload = constructPayloadFromFormData(form);
validate(payload).then(function(v) {
console.log("response Data:");
for(let p in v) {
if(v.hasOwnProperty(p)) {
constructInvalidFeedbackForProperty(p,v[p])
}
}
});
}
this function constructs a payload from the form data (working fine) then executes another ajax call inside of validate() - I wait for the return call from ajax and then iterate through an array of validation data to confirm the form's validity. However, here is where the problem is:
function constructInvalidFeedbackForProperty(prop,e) {
let el = $("#" + "ic-role-" + prop);
console.log(el);
el.append("<div class=\"invalid-feedback\">problem</div>");
}
the problem is the append - I cannot seem to fire that method. I can select the element as the console.log(el) writes to the log the correctly identified element in my dom.
What am I doing wrong?
I have created a contrived jsfiddle for a sample of the problem. I actually believe it may be that an input field is not something you can append to... perhaps? https://jsfiddle.net/jtango/xpvt214o/987051/
Okay, I messed around with your fiddle a bit. If you inspect the input element that is created you can see that your append does work. It's just not displaying. If you are trying to edit what is in the input box then you must use val()
Here is a copy of your fiddle that will display inside the input:
$("#top").on("click", function(){
$("#form").append("<label>some label: </label><input type=\"text\" id=\"myinput\">");
});
$("#btm").on("click",function(){
$("#myinput").val("<div>I will not appear</div>");
});
As your shared https://jsfiddle.net/jtango/xpvt214o/987051/ It will not appear, this is wrong way to append any HTML element inside "input box" or any of form elements. it should allow to set only new attribute or value.
check screenshot: https://i.stack.imgur.com/4FBgn.png
So verify your below code if it's similar then it will not work:
let el = $("#" + "ic-role-" + prop);
console.log(el);
el.append("<div class=\"invalid-feedback\">problem</div>");

Angular2-modal confirm callback

I am programming in an Angular 2 project. I have a several component where I want to use the same dialogue confirm box. Therefore i have put the confirm code in a separate class. The dialogue box is supposed to check whether a user wants to continue or save data.
I am using Angular2-modal for this pupose.
When either button on the confirm is pressed, I want to be able to return this answer to the component that called this confirm so I can perform certain actions there.
My code looks like this:
This is the function I call from my component:
this._popup.confirmSaveTemp(this.modal);
This is the function with the confirm code. Currently I can print out OK or cancel in the two spots where I have placed "TODO".
confirmSaveTemp(modal, target, param){
console.log(target);
modal.confirm()
.size('lg')
.isBlocking(true)
.showClose(false)
.keyboard(27)
.title('Warning')
.body(`
<p><b>Some fields have been <span class="text-danger">marked with red</span> because of one or several following reasons:</b></p>
<ul>
<li>You forgot to fill out all input fields</li>
<li>Entered values are unrealistically high or low</li>
<li>Use of illegal characters (e.g. typing letters instead of numbers for a persons age)</li>
</ul>
<p><b>Please make sure that you have filled out the form correctly.</b></p>
<p>
<b>If you are finished entering all values for this page and want to permanently save, click <span class="text-success">Continue</span>.</b>
<br>
<b>If you expect to enter the remaining values at another time click <span class="text-warning">Save Temporarily</span></b>
</p>
<p></p>
`)
.footerClass('defaultPopupFooter')
.okBtn('Continue')
.cancelBtn('Save Temporarily')
.okBtnClass('btn btn-success')
.cancelBtnClass('btn btn-warning')
.open()
.then( (resultPromise) => {
resultPromise.result.then( (result) => {
//TODO - CALL SAVE FUNCTION
},
() => {
//TODO - SAVE TEMP
} );
});
}
* Question: How can I inform the "parent" component what the response of this dialogue is OR how can call a function from the "parent" component? *
You can pass functions as parameters like this from the parent class:
private okCallback() {
// do stuff on ok
}
private cancelCallback() {
// do stuff on cancel
}
openModal() {
// ...
this._popup.confirmSaveTemp(
this.modal,
target,
param,
this.okCallback.bind(this),
this.cancelCallback.bind(this)
);
}
And in the confirmSaveTemp:
confirmSaveTemp(modal, target, param, okCallback, cancelCallback){
console.log(target);
modal.confirm()
// ...
.open()
.then( (resultPromise) => {
resultPromise.result.then( (result) => {
//TODO - CALL SAVE FUNCTION
},
() => {
//TODO - SAVE TEMP
} );
})
// on OK click
.then(okCallback)
// on Cancel click
.catch(cancelCallback);
}

Categories

Resources