How to seperate Vue logic in a laravel app based on layout and page templates - forms

I have a laravel app and a Vue instance attached to the body (or a div, just inside the body).
const app = new Vue({
el: '#app'
});
I think it makes sense to use the Vue instance for stuff relating to the layout (eg header, nav, footer logic).
Now I have a form that is visible on a specific route (e.g. example.com/thing/create). I want to add some logic to it, e.g. hiding a field based on selected option in the form. It is logic meant for just this form (not to be reused). I prefer not to put all the logic inline with the form but put it in the app.js. I could put it in the Vue instance bound to the body but that sounds odd as it only applies to the form that is much deeper into the dom.
I want to leave the markup of the form in the blade template (that inherits the layout).
I tried creating a component but am not sure how to bind this inside the main Vue instance. What is the best way to handle things for this form, put it in the app.js and have it somewhat structured, putting the variables somewhat into scope. Or is it really necessary to remove the main Vue instance bound to the full layout code?
What I tried was something like this, but it does not work (attaching it to the <form id="object-form"> seems to fail:
var ObjectForm = {
template: function() { return '#object-form'},
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
}
};
Things do work if I remove the #app Vue instance or when I put everything directly in the app Vue instance. But that seems messy, if I have similar variables for another form they should be seperated somewhat.
I would appreciate some advice regarding the structure (differentiate page layout and page specific forms) and if possible some example to put the form logic inside the main app.js.

I hope this helps kind of break things down for you and helps you understand Vue templating.
It is best to take advantage of Vue's components. For you it would look something like this. Some of this code depends on your file structure, but you should be able to understand it.
In your app.js file (or your main js file)
Vue.component('myform',require('./components/MyForm.vue'));
const app = new Vue({
el: "#app"
});
Then create the MyForm.vue file
<template>
<form>
Put Your Form Markup Here
</form>
</template>
<script>
// Here is where you would handle the form scripts.
// Use methods, props, data to help set up your component
module.exports = {
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
},
methods: {
// add methods for dynamically changing form values
}
}
</script>
Then you will be able to just call in your blade file.
<myform></myform>

I found out how to do it. The trick was to use an inline template. Surround the form in the view with:
<object-form inline-template>
<form>...</form>
</object-form>
Where object-form is the name of the component. In the ObjectForm code above I remove the template, like this:
var ObjectForm = {
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
}
};
I attach the component within the root vue app like this:
const app = new Vue({
el: 'body',
components: {
'object-form': ObjectForm
}
});
This way I can use the form as it was generated from the controller and view and I can separate it from the root (attached to body) methods and properties.
To organize it even better I can probably store the ObjectForm in a seperate .vue file the way #Tayler Foster suggested.

Related

Angular 2 - Provide 3rd-party library with element for rendering

How would I provide a DOM element to a 3rd-party library in Angular 2?
For example, if Library is the hypothetical 3rd-party library, and I had to do something like:
var fakeId = document.getElementById('fake'); // e.g. canvas or SVG element
var sirRender = Library.confiscate(fakeId);
sirRender.drawMustache(); // accesses canvas context or manipulates SVG
I am using Typescript and ES6 decorator component syntax.
I'm imagining I can do something inside ngOnInit like:
#Component({
...
})
export class SirRender {
...
ngOnInit() {
// do something here?
}
...
}
My specific use case:
I'm trying to use this library called VexFlow, which takes a canvas element and renders svg. Specifically, there is an example:
var canvas = $("div.one div.a canvas")[0];
var renderer = new Vex.Flow.Renderer(canvas, Vex.Flow.Renderer.Backends.CANVAS);
var ctx = renderer.getContext();
var stave = new Vex.Flow.Stave(10, 0, 500);
stave.addClef("treble").setContext(ctx).draw();
So, I'm hoping the answer will work for this ^^ case.
In fact you can reference the corresponding ElementRef using #ViewChild. Something like that:
#Component({
(...)
template: `
<div #someId>(...)</div>
`
})
export class Render {
#ViewChild('someId')
elt:ElementRef;
ngAfterViewInit() {
let domElement = this.elt.nativeElement;
}
}
elt will be set before the ngAfterViewInit callback is called. See this doc: https://angular.io/docs/ts/latest/api/core/ViewChild-var.html.
For HTML elements added statically to your components template you can use #ViewChild():
#Component({
...
template: `<div><span #item></span></div>`
})
export class SirRender {
#ViewChild('item') item;
ngAfterViewInit() {
passElement(this.item.nativeElement)
}
...
}
This doesn't work for dynamically generated HTML though.
but you can use
this.item.nativeElement.querySelector(...)
This is frowned upon though because it's direct DOM access, but if you generate the DOM dynamically already you're into this topic already anyway.

Ember Observe DOM Element

I have an
<input type="file">
in my DOM. Is it possible to trigger an action with Ember techniques if the file in this input changes, or do I have to use third party libs like jquery-observe?
Yes, of course it is possible.
You can create a file field component as follows:
// put in components/file-field.js if you are using ember-cli
import Ember from "ember"
export default Ember.TextField.extend({
type: 'file',
attributeBindings: ['multiple'],
multiple: false,
change: function(event) {
var input = event.target();
if (!Ember.isEmpty(input.files)) {
this.sendAction("filesChanged", input.files);
}
}
});
Now place this in your template in place of your <input type="file">
{{file-field filesChanged="uploadFile"}}
Then in the controller or in one of your routes where this action will bubble, define your uploadFile action:
actions: {
uploadFile: function(files) {
// put your ajax call to upload the file(s) here
}
}
Although this is enough to get you started learning, I would definitely recommend using something like ember-cli-uploader for this in a real application.

Best practices when editing form with emberjs

Is there any good solutions when editing a form to save the model only if the user clicked on the save button and retrieve the old datas if the user canceled the action ?
I've seen some solutions like duplicating the object that is data-binded with each form fields and set the the initial object with the duplicated one when it is saved.
If you could give answers without using ember data could be great.
I understand you would prefer a solution that doesn't use ember-data, but I would argue that using ember-data is best practices. Here is a solution using ember-data because I imagine a lot of people may come across this question...
If you set up your route as follows, it will do exactly that.
App.CommentEditRoute = Em.Route.extend({
model: function(params) {
return this.store.find('comment', params.comment_id);
},
actions: {
willTransition: function(transition) {
var model = this.get('controller.content');
if (model.get('isDirty')) {
model.rollback();
}
}
},
});
If you call this.get('content').save() in the controller (because the user clicked the save button) it will persist the changes through the adapter and isDirty will be set to false. Thus, the model will not rollback. Otherwise, if you did not call this.get('content').save() in the controller, the isDirty property will be true and the unsaved changes will be discarded. See the DS.Model docs for more info.
willTransition is an event automatically called when the route is about to change - you don't have to call it directly.
Your controller might look like this:
App.CommentEditController = Em.ObjectController.extend({
save: function() {
var _this = this;
_this.get('content').save().then(function() {
// Success
_this.transitionToRoute('comments');
}, function() {
// Failure
Em.assert('Uh oh!');
});
},
cancel: function() {
this.transitionToRoute('comments');
},
});
Also, be sure to utilize the default HTML form submission using a proper HTML button or input for submission so you can capture the submission event in your view as follows:
App.CommentEditView = Em.View.extend({
submit: function() {
this.get('controller').save();
},
});

How to manipulate forms with Mootools

I'm trying to manipulate forms with Mootools. My purpose is to inject the response content of a form into a div element named result.
Here a code that works, but it replaces the content of the result div. This is not what I want : I want to ADD the form response content to the result div existing content. I just can't find on the web how to do this, and I've tried many things that are not working ... Please help
window.addEvent('domready', function() {
$('myform').addEvent('submit', function(e) {
e.stop();
var result = $('result').empty();
this.set('send',{
url: this.get('action'),
data: this,
onSuccess: function() {
result.set("html", this.response.text);
}
}).send();
});
});
If it's only text you want to add, just remove the empty method, and replace result.set() with result.appendText().
If you need to append an element tree, repeat the first step, and do:
onSuccess: function(){
Elements.from(this.response.text).inject(result);
}
Btw. It's all in the documentation - http://mootools.net/docs/core/Element/Element

jquery selection with .not()

I have some troubles with jQuery.
I have a set of Divs with .square classes. Only one of them is supposed to have an .active class. This .active class may be activated/de-activated onClick.
Here is my code :
jQuery().ready(function() {
$(".square").not(".active").click(function() {
//initialize
$('.square').removeClass('active');
//activation
$(this).addClass('active');
// some action here...
});
$('.square.active').click(function() {
$(this).removeClass('active');
});
});
My problem is that the first function si called, even if I click on an active .square, as if the selector was not working. In fact, this seems to be due to the addClass('active') line...
Would you have an idea how to fix this ?
Thanks
Just to give something different from the other answers. Lonesomeday is correct in saying the function is bound to whatever they are at the start. This doesn't change.
The following code uses the live method of jQuery to keep on top of things. Live will always handle whatever the selector is referencing so it continually updates if you change your class. You can also dynamically add new divs with the square class and they will automatically have the handler too.
$(".square:not(.active)").live('click', function() {
$('.square').removeClass('active');
$(this).addClass('active');
});
$('.square.active').live('click', function() {
$(this).removeClass('active');
});
Example working: http://jsfiddle.net/jonathon/mxY3Y/
Note: I'm not saying this is how I would do it (depends exactly on your requirement) but it is just another way to look at things.
This is because the function is bound to elements that don't have the active class when you create them. You should bind to all .square elements and take differing actions depending on whether the element has the class active:
$(document).ready(function(){
$('.square').click(function(){
var clicked = $(this);
if (clicked.hasClass('active')) {
clicked.removeClass('active');
} else {
$('.square').removeClass('active');
clicked.addClass('active');
}
});
});