Proper DOM event for when an HTML template is to be made (with VueJS) - dom

I want to run a METHOD when a template element is rendered but I'm not sure which DOM event to use:
<template v-on:something="method(parameter)">
</template>

Try mounted (One of Vue's life cycle hooks):
mounted: function() {
console.log("Your Vue application is mounted!");
}

use updated()
updated()
{
this.testing(parameter);
},
methods:{
testing:function(parameter){
try {
//code
}
catch(err) {
console.log(err);
}
}
}
http://www.laraphp.com/initialize-js-functions-vue-jsmaterialize-modal-popup-auto-initialize/

Related

Setting focus on page load in Ionic

I can't seem to get focus to set on page load. Here is what I'm trying to do right now:
INPUT:
<ion-input placeholder="SCAN LP TO ACKNOWLEDGE" type="number" [(ngModel)]="this.session.listService.licensePlate" required (keyup.enter)="ValidateAndAcknowledge()" #myInput ></ion-input>
TS FILE
export class AcknowledgePage {
#ViewChild('input') myInput;
constructor() {
}
ionViewDidLoad() {
setTimeout(() => {
console.log(this.myInput);
this.myInput.setFocus();
}, 150);
}
}
So your ViewChild refers 'input' while your template states #myInput. You need to fix that:
export class AcknowledgePage {
#ViewChild('myInput') myInput;
constructor() {
}
ionViewDidLoad() {
setTimeout(() => {
console.log(this.myInput);
this.myInput.setFocus();
}, 150);
}
}
Now even if this code will work for you on Android devices - this may not work on latest iOS (11.3+) since Apple actually wants users to trigger focus via explicit tap action and not programmatic-ally.
I don't know why but #viewChild is not working for me at the end I used document.querySelector() in ionViewDidLoad() and set focus() and It's work for me.

Refresh custom control in sapui5 when model change

I've a custom control which have multiple properties inserted in Detail View page. I've binded data with these properties. Scenario is I've two pages one is list view and then detail view. I've to navBack from detail page and select diff product from main page.Detail view page show diff products detail according to selected product. everything works fine. but problem is that my custom control doesn't update values and other page have updated values.
<custom:product topic="" subTopic="{product>name}" id="productDetial"></custom:product>
I've used one methond this.getView().byId("productDetail").rerender(); but it doesn't update my Inner HTML of control.
the control code. might be some typos error.as I've changed some variables name and remove unwanted code. the purpose is to show the methods which I've used and how I did
sap.ui.define([
"sap/m/Label",
"sap/m/Button",
"sap/m/CustomTile"
], function(Label, Button, CustomTile) {
"use strict";
jQuery.sap.declare("testProduct.control.product");
return CustomTile.extend("testProduct.control.product", {
metadata: { // the Control API
properties: {
name: {
type: "string",
defaultValue: "--"
},
subTopic: {
type: "string",
defaultValue: "--"
}
}
},
init: function() {
},
rerender: function(oRM, oControl) {
},
renderer: function(oRM, oControl) {
oRM.write('<div class=" sapMTile customTileCourseDetail">');
oRM.write('<div class="leftTileYourScore">');
if (oControl.getSubTopic() !== "" && oControl.getSubTopic() !== undefined) {
oRM.writeEscaped(oControl.getSubTopic());
} else {
oRM.write(" ");
}
oRM.write('</div>');
oRM.write('</div>
}
});
});
Yo just need to add a setter function in you control. When the binding is refreshed/changes, UI5 will trigger a setter method specific to the property. So in you case for the property subTopic it expects a method setSubTopic. This method should define you own logic to update said property in the UI layer according to your needs.
Here is part of the code you need to add, you will also have to tweak the initial rendering logic a bit.
renderer: function (oRM, oControl) {
//oRM.write('<div class=" sapMTile customTileCourseDetail">');
oRM.write("<div")
oRM.writeControlData(oControl);
oRM.addClass("sapMTile customTileCourseDetail");
oRM.writeClasses();
oRM.write(">");
oRM.write('<div class="leftTileYourScore">');
if (oControl.getSubTopic() !== "" && oControl.getSubTopic() !== undefined) {
oRM.writeEscaped(oControl.getSubTopic());
} else {
oRM.write(" ");
}
oRM.write('</div>');
oRM.write('</div>');
},
setSubTopic: function(sText){
this.setProperty("subTopic", sText, true);
$("#"+this.sId+" .leftTileYourScore").html(sText);
}

What is sane way in vuejs + vuex form handling?

I have a large forms to submit in single page.
<container>
<formA>
<formB>
<formC>
<submitButton>
<container>
it looks apparently like this. and I have a store which save every form data. then when user click submit button, I gather all form data using vuex store.
The problem is I need to update the form data in store everytime.
so I'll be like this in vue component
watch: {
userInput (val) {
this.updateState(val)
}
update state when input changes by watching form data(binded with v-model).
or like this which is documented in vuex doc.
userInput: {
get () {
return this.$store.state.userInput
},
set (val) {
this.updateState(val)
}
}
well.. I don't think these are good idea. Is there any better way to form handling with vuex?
I made a little tool which makes form handling wit Vuex a lot easier: vuex-map-fields
Example
Store
import Vue from 'vue';
import Vuex from 'vuex';
// Import the `getField` getter and the `updateField`
// mutation function from the `vuex-map-fields` module.
import { getField, updateField } from 'vuex-map-fields';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
fieldA: '',
fieldB: '',
},
getters: {
// Add the `getField` getter to the
// `getters` of your Vuex store instance.
getField,
},
mutations: {
// Add the `updateField` mutation to the
// `mutations` of your Vuex store instance.
updateField,
},
});
Component
<template>
<div id="app">
<input v-model="fieldA">
<input v-model="fieldB">
</div>
</template>
<script>
import { mapFields } from 'vuex-map-fields';
export default {
computed: {
// The `mapFields` function takes an array of
// field names and generates corresponding
// computed properties with getter and setter
// functions for accessing the Vuex store.
...mapFields([
'fieldA',
'fieldB',
]),
},
};
</script>
You can read more about vuex-map-fields on my blog: How to Handle Multi-row Forms with Vue, Vuex and vuex-map-fields
I would use deep watchers for this and have all fields in a object, you could use multiple approaches for saving the data, iterating over Object.keys to store each field with it's variable name in the form object, or storing the entire form, whatever you might need.
You could also use v-model.lazy="form.myfield" to indicate that you only want the binding to update once the user has left the field.
Form component
<template>
<div>
<!-- You can optionally use v-model.lazy="form.field1" to only update once user has exited the field or pressed enter -->
<input v-model="form.field1" />
<input v-model.lazy="form.field2" />
</div>
</template>
<script>
export default {
props: ['value'],
data: function () {
return {
internalForm: {
field1: null,
field2: null
}
}
},
watch: {
internalForm: {
handler: function (newValue) {
// Emit new form object to parent component so we can use v-model there
this.$emit('input', this.form)
// Or save form data
this.handleFormSave(this.form)
},
// Tell vue to do a deep watch of entire form object to watch child items in the object
deep: true
}
}
}
</script>
Parent component
<template>
<form-component v-model="forms.form1" />
<submit-button #click="saveAllFormData" />
</template>
<script>
export default {
data: function () {
return {
forms: {
form1: null // This will be updated when 'input' is emitted
}
}
},
watch: {
forms: {
handler: function (newValue) {
if (allFormsValid && readyToSave)
saveAllFormData(newValue);
},
deep: true
}
}
}
</script>
I had headache regarding this probem to.
Vuex doc describes that we need to update store for every field.
It's a loot of typing whatfor?
We make one solution that works.
It based on cloning store object to local one.
//We are passing (vuexstore) 'item' object from parent component:
//<common-item v-bind:item="item" ....
props: ['item'],
// create localItem - this is reactive object for vuex form
data: () => {
return {
localItem: null
}
},
// make clone on created event
created: function() {
this.localItem = this._clone(this.item)
},
// watch vuexstore 'item' for changes
watch: {
item: function(val) {
this.localItem = this._clone(this.item)
}
},
// map mutations and update store on event
methods: {
...mapMutations([
'editItem'
]),
updateItemHandler: function() {
this.editItem({ item: this._clone(this.localItem) })
},
_clone: function(o){
return JSON.parse(JSON.stringify(o))
}
},
Inside form use:
<input v-model="localItem.text" #keyup="updateItemHandler" type="text" class="form-control"></input>
I think this is only lack of vuex. There should be much shorter and built in solution.

How do I trigger tinymce 4.x focus and blur events

I realize that this question has been asked and answered several times, but I still can't make many of the solutions work. It seems like most of the discussions are older and maybe not compatible with 4.x.
My goal: be able fire some javascript functions upon focus or blur. Here's the base code:
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
});
I tried examples like:
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
var dom = ed.dom;
var doc = ed.getDoc();
tinymce.dom.Event.add(doc, 'blur', function(e) {
alert('blur!!!');
});
});
}
});
returns:"Uncaught TypeError: Cannot call method 'add' of undefined"
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
});
tinymce.activeEditor.on('focus', function(e) {
console.log(e.blurredEditor);
});
returns: "Uncaught TypeError: Cannot call method 'on' of undefined"
(but not sure if I have it in the right place)
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
setup: function(editor) {
editor.on('focus', function(e) {
console.log('focus event', e);
});
}
});
returns: "Uncaught SyntaxError: Unexpected identifier"
This works but only when initiating the editor. Other things I've tried but haven't gotten to work:
tinymce.FocusManager
tinymce.activeEditor
What am I missing? Thanks.
UPDATE: found a solution that worked beautifully: Why TinyMCE get focus and blur event, when user jump from other input field?
see the fiddle at http://fiddle.tinymce.com/8Xeaab/1
tinymce.init({
selector: "#editme",
inline: true,
setup: function(editor) {
editor.on('focus', function(e) {
console.log("focus");
});
editor.on('blur', function(e) {
console.log("blur");
});
}
});
Your cuestion title its about TRIGGERING focus and blur events, but you really are asking about HANDLING those events.
If anybody is still looking for triggering the events, the solution should by:
tinymce.init({
selector: "#textarea_123",
...
});
then, to set focus:
var inst = tinyMCE.EditorManager.get('textarea_123');
inst.focus();
I recently ran into this issue and although I am doing this in angularjs I was able to implement a fix for it by creating a directive that registers when you click off of it and then clears the activeElement in the html body. I will add the directive below. You just call it on the object by adding click-off like you would an ng-cloak to a tag.
(function () {
'user strict';
angular.module('app.directives').directive('clickOff', ClickOff);
function ClickOff($parse, $document) {
var directive = {
link: link
};
return directive;
function link(scope, $element, attr) {
var fn = $parse(attr["clickOff"]);
$element.bind('click', function (event) {
event.stopPropagation();
});
angular.element($document[0].body).bind("click", function (event) {
scope.$apply(function () {
$document[0].activeElement.blur();
fn(scope, { $event: event });
});
});
}
}
})();

Meteor: apply function after rendering things from mongodb

I am using sage cell to convert html to math stuff
Template.home.rendered = function(){
\\ apply sagecell and mathjax
}
However, the content that are rendered comes from mongo, so it's sometimes loaded after sage cell is applied to it. I can do something like this
Template.home.rendered = function(){
Deps.autorun(function(){
if (Content.findOne({_id: ...})){
\\ apply sagecell and mathjax
}
});
}
It's better but still doesn't work all the time. Is there other things I can use to detect the content is completely rendered?
Edited with new response:
<template name='pendingAnswer'>
The answer to your question, coming back whenever, is:
{{>answer}}
</template>
<template name='answer'>
{{fromSage}}
</template>
Template.answer.helpers({
fromSage: function () {
Session.get('fromSage');
}
});
Invoked whenever - from a button, from navigating to the page, on blur...
function GetAnswerFromSage(data) {
callHTTP(website,data, callbackFromSage)
}
function callbackFromSage(err, data) {
if (err) then log(err);
Session.set('fromSage', data);
}
Earlier: try transform upon retrieval of mongo:
From Meteor Doc
// An Animal class that takes a document in its constructor
Animal = function (doc) {
_.extend(this, doc);
};
_.extend(Animal.prototype, {
makeNoise: function () {
console.log(this.sound);
}
});
// Define a Collection that uses Animal as its document
Animals = new Meteor.Collection("Animals", {
transform: function (doc) { return new Animal(doc); }
});
// Create an Animal and call its makeNoise method
Animals.insert({name: "raptor", sound: "roar"});
Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"
The script
<script type='text/javascript' src="http://sagecell.sagemath.org/static/embedded_sagecell.js"></script>
that is supposed to be in the head needs to be removed and instead be loaded after the content is completely loaded like so:
Template.content.rendered = function(){
// sage
Deps.autorun(function(){
if (Session.get('contentChanged')){
// loading this script causes mathjax to run
$.getScript("http://sagecell.sagemath.org/static/embedded_sagecell.js", function(d, textStatus){
if (textStatus=='success'){
// this converts <div class='compute'> to a sage cell
sagecell.makeSagecell({
inputLocation: 'div.compute',
evalButtonText: 'Evaluate',
hide: ['editorToggle']
});
}
})
}
})
and if I go from 1 content template to another content template, it seems that nothing is rerendered and so the mathjax was not applied. The only fix I can think is to force a page reload:
Template.content.events({
'click a': function(evt){
evt.preventDefault();
location.href = evt.currentTarget.href;
}
})
which makes the site much slower, unfortunately.