Access values after form-pre-filling (with Ember.js) - javascript

I have one form for saving and editing records. On clicking on a record, the form should be filled with the data. After filling, I want to do some UI actions (call jQuery Plugin etc.).
The pre-filling works, but when I'm trying to access the values, it works only at the second click. On the first click, the values are empty or the ones from the record clicked before.
This action is stored in the controller:
edit: function(id) {
var _this = this;
// prefill form for editing
var customer = this.store.find('customer', id).then(function(data) {
_this.set('name',data.get('name'));
_this.set('number',data.get('number'));
_this.set('initial',data.get('initial'));
_this.set('description',data.get('description'));
_this.set('archived',data.get('archived'));
// store user for save action
_this.set('editedRecordID',id);
_this.set('isEditing',true);
$('input[type="text"]').each(function() {
console.log(this.value)
});
});
},
I need a generic way to check if the input field is empty, because I want to include this nice UI effect: http://codepen.io/aaronbarker/pen/tIprm
Update
I tried to implement this in a View, but now I get always the values from the record clicked before and not from the current clicked element:
View
Docket.OrganizationCustomersView = Ember.View.extend({
didInsertElement: function() {
$('input[type="text"]').each(function() {
console.log(this.value)
});
}.observes('controller.editedRecordID')
});
Controller
Docket.OrganizationCustomersController = Ember.ArrayController.extend({
/* ... */
isEditing: false,
editedRecordID: null,
actions: {
/* ... */
edit: function(id) {
var _this = this;
// prefill form for editing
var customer = this.store.find('customer', id).then(function(data) {
_this.set('name',data.get('name'));
_this.set('number',data.get('number'));
_this.set('initial',data.get('initial'));
_this.set('description',data.get('description'));
_this.set('archived',data.get('archived'));
// store user for save action
_this.set('editedRecordID',id);
_this.set('isEditing',true);
});
},
/* ... */
});
Update 2
OK, I think I misunderstood some things.
At first, my expected console output should be:
1.
2.
3.
but is:
1.
3.
2.
Secondly: I can use any name, even foobar, for the observed method in my view. Why?
Controller
edit: function(id) {
var _this = this;
// prefill form for editing
var customer = this.store.find('customer', id).then(function(data) {
_this.set('name',data.get('name'));
_this.set('number',data.get('number'));
_this.set('initial',data.get('initial'));
_this.set('description',data.get('description'));
_this.set('archived',data.get('archived'));
console.log('1.')
// store user for save action
_this.set('editedRecordID',id);
_this.set('isEditing',true);
console.log('2.')
});
},
View
Docket.OrganizationCustomersView = Ember.View.extend({
foobar: function() {
console.log('3.')
$('input[type="text"]').each(function() {
console.log(this.value)
});
}.observes('controller.editedRecordID')
});
Update 3
I think I "figured it out" (but I don't know why):
Docket.OrganizationCustomersView = Ember.View.extend({
movePlaceholder: function() {
$('input[type="text"], textarea').bind("checkval",function() {
var $obj = $(this);
setTimeout(function(){
console.log($obj.val());
},0);
}.observes('controller.editedRecordID')
});
setTimeout(function(){ ... }, 0); does the trick. But why?!

You can convert use that jquery code in a component, this is the best way to create a reusable view, without putting ui logic in controllers, routers etc.
Template
<script type="text/x-handlebars" data-template-name="components/float-label">
<div class="field--wrapper">
<label >{{title}}</label>
{{input type="text" placeholder=placeholder value=value}}
</div>
</script>
FloatLabelComponent
App.FloatLabelComponent = Ember.Component.extend({
onClass: 'on',
showClass: 'show',
checkval: function() {
var label = this.label();
if(this.value !== ""){
label.addClass(this.showClass);
} else {
label.removeClass(this.showClass);
}
},
label: function() {
return this.$('input').prev("label");
},
keyUp: function() {
this.checkval();
},
focusIn: function() {
this.label().addClass(this.onClass);
},
focusOut: function() {
this.label().removeClass(this.onClass);
}
});
Give a look in that jsbin http://emberjs.jsbin.com/ILuveKIv/3/edit

Related

Affecting other views in Marionette

I am working in Marionette and have an accordion which we have set up so that the individual panels are templates that are called in and created by
var AccorionView = require(“../folder/AccordionView”);
var expandButtons = require(“../folder/expandButtons”);
var MainPage = Marionette.View.extend({
regions: {
region: “.region”,
button: “.buttons”
},
this.newAccordion = new AccordionView({
header: “header goes here”,
childView: new panelView(),
});
this.showChildView(‘region’, this.newAccordion);”
I am going to pull in another view with the actual Expand/Collapse All button in it, which will expand and collapse all of the accordion panels on this page. The JavaScript that would be used on this page would be
expandAll: function() {
this.newAccordion.expand();
},
However, this function will be put into the new JavaScript view of the buttons. I am going to send the names of the accordion panels to the button view when calling it into this page, but how do I get the function on that view to influence the accordion panels on this main page?
I would use Backbone.Radio in this case:
const Radio = require('backbone.radio');
const accorionChannel = Radio.channel('accorion');
const MainPage = Marionette.View.extend({
// ...
initialize() {
accorionChannel.on('expand', function() {
this.newAccordion.expand();
});
accorionChannel.on('unexpand', function() {
this.newAccordion.unexpand();
});
}
// ...
});
const WhateverView = Marionette.View.extend({
someEventHandler() {
accorionChannel.trigger('expand');
// OR
accorionChannel.trigger('unexpand');
}
});
Radio channel is singleton, you can create a new one every time but it will refer to the same channel. This saves you from passing the channel variable around or having a global variable.
You can do this one of two ways
1) With triggers/childViewEvents
// in expandButtons
expandButtons = Marionette.View.extend(
triggers: {
'click #ui.expandAll': 'expandAll'
}
);
// in MainPage
MainPage = Marionette.View.extend({
childViewEvents: {
'expandAll': 'expandAll'
},
expandAll: function(child) {
this.newAccordion.expand();
// OR
this.getChildView('region').expand();
}
})
OR
2) With Backbone.Radio
// in expandButtons
var Radio = require('Backbone.Radio');
var expandChannel = Radio.channel('expand');
var expandButtons = Marionette.View.extend({
events: {
'click #ui.expandAll': 'expandAll'
},
expandAll: function(e) {
expandChannel.trigger('expand:all');
}
});
// in AccordionView
var AccordionView = Marionette.View.extend({
channelName: 'expand',
radioEvents: {
'expand:all': 'expand' // triggers this.expand();
}
});
In this case, it might be even easier to do #2 but instead of adding the radio listener to the AccordionView, attach the listeners to the PanelView (AccordionView's childView). This is because AccordionView's expand function will likely have to iterate each of its children like:
this.children.each(function(childView) {
childView.expand();
});

jQuery click or touchstart event is not working on mobile

I am using intl-tel-input to get peoples phone code and country. When they select the flag and code I have some jQuery with gets the country and code separately and populates hidden fields...
Here is the entire object which handles these operations:
var telInput = {
init: function(){
this.setTelInput();
this.cacheDOM();
this.bindEvents();
},
cacheDOM: function(){
this.$countryCode = $('input[name=country_code]');
this.$countryName = $('input[name=country_name]');
this.$country = $('.country');
},
bindEvents: function(){
this.$country.on('click', this.getTelInput.bind(this));
},
setTelInput: function(){
$('input[name=phone]').intlTelInput({
preferredCountries: [
'gb'
],
});
},
getTelInput: function(e){
var el = $(e.target).closest('.country');
var countryCode = el.attr('data-dial-code');
var countryName = el.find('.country-name').text();
this.$countryCode.val(countryCode);
this.$countryName.val(countryName);
},
}
Problem
The problem is the click event in the bindEvents method... the phone picker works but the onclick event is not being triggered to populate my hidden fields.
You need to make sure that you cache the DOM after it has been rendered. Here's a simplified example.
View on jsFiddle
var telInput = {
init: function(){
this.cacheDOM();
this.bindEvents();
},
cacheDOM: function() {
this.$country = $('.country');
},
bindEvents: function() {
this.$country.on('click', function() {
// console.log('Triggered');
});
}
}
$(document).ready(function() {
telInput.init();
});
Also, plugin's event countrychange could be useful in your case.
$("#country-select-element").on("countrychange", function(e, countryData) {
// do something with countryData
});
I would also suggest you to have a look at the public methods. It has some useful methods that you could use to achieve the same result.

Making a template helper reactive in Meteor

I am building a chat application and on my "new chats" page I have a list of contacts, which you can select one by one by tapping them (upon which I apply a CSS selected class and push the user id into an array called 'newChatters'.
I want to make this array available to a helper method so I can display a reactive list of names, with all users who have been added to the chat.
The template that I want to display the reactive list in:
<template name="newChatDetails">
<div class="contactHeader">
<h2 class="newChatHeader">{{newChatters}}</h2>
</div>
</template>
The click contactItem event triggered whenever a contact is selected:
Template.contactsLayout.events({
'click #contactItem': function (e) {
e.preventDefault();
$(e.target).toggleClass('selected');
newChatters.push(this.username);
...
The newChatters array is getting updated correctly so up to this point all is working fine. Now I need to make {{newChatters}} update reactively. Here's what I've tried but it's not right and isn't working:
Template.newChatDetails.helpers({
newChatters: function() {
return newChatters;
}
});
How and where do I use Deps.autorun() to make this work? Do I even need it, as I thought that helper methods auto update on invalidation anyway?
1) Define Tracker.Dependency in the same place where you define your object:
var newChatters = [];
var newChattersDep = new Tracker.Dependency();
2) Use depend() before you read from the object:
Template.newChatDetails.newChatters = function() {
newChattersDep.depend();
return newChatters;
};
3) Use changed() after you write:
Template.contactsLayout.events({
'click #contactItem': function(e, t) {
...
newChatters.push(...);
newChattersDep.changed();
},
});
You should use the Session object for this.
Template.contactsLayout.events({
'click #contactItem': function (e) {
//...
newChatters.push(this.username);
Session.set('newChatters', newChatters);
}
});
and then
Template.newChatDetails.helpers({
newChatters: function() {
return Session.get('newChatters');
}
});
You could use a local Meteor.Collection cursor as a reactive data source:
var NewChatters = new Meteor.Collection("null");
Template:
<template name="newChatDetails">
<ul>
{{#each newChatters}}
<li>{{username}}</li>
{{/each}}
</ul>
</template>
Event:
Template.contactsLayout.events({
'click #contactItem': function (e) {
NewChatters.insert({username: this.username});
}
});
Helper:
Template.newChatDetails.helpers({
newChatters: function() { return NewChatters.find(); }
});
To mimick the behaviour of Session without polluting the Session, use a ReactiveVar:
Template.contactsLayout.created = function() {
this.data.newChatters = new ReactiveVar([]);
}
Template.contactsLayout.events({
'click #contactItem': function (event, template) {
...
template.data.newChatters.set(
template.data.newChatters.get().push(this.username)
);
...
Then, in the inner template, use the parent reactive data source:
Template.newChatDetails.helpers({
newChatters: function() {
return Template.parentData(1).newChatters.get();
}
});
for people who is looking for a workaround for this in the year 2015+ (since the post is of 2014).
I'm implementing a posts wizard pw_module where I need to update data reactively depending on the route parameters:
Router.route('/new-post/:pw_module', function(){
var pwModule = this.params.pw_module;
this.render('post_new', {
data: function(){
switch (true) {
case (pwModule == 'basic-info'):
return {
title: 'Basic info'
};
break;
case (pwModule == 'itinerary'):
return {
title: 'Itinerary'
};
break;
default:
}
}
});
}, {
name: 'post.new'
});
Later in the template just do a:
<h1>{{title}}</h1>
Changing routes
The navigation that updates the URL looks like this:
<nav>
Basic info
Itinerary
</nav>
Hope it still helps someone.

KnockoutJS/Bootstrap - Clearing modal form when closing modal using javascript

I have a Bootstrap Modal that contains a form for updating or creating an entity (Company in my example). Right now my issue is that if I view an entity using the modal, it doesn't clear out the fields when I close the modal by any means. Causing the form to still be populated if I then click a "Create" button, which should bring me up a blank modal.
How can I execute one of my ViewModels methods from just regular javascript? Here is some of my code:
function ViewModel() {
var self = this;
function CompanyViewModel(company) {
var self = this;
self.Id = company.CompanyId;
self.Name = company.Name;
}
function BlankCompanyViewModel() {
var self = this;
self.Id = 0;
self.Name = "";
}
self.company = ko.observable();
self.companies = ko.observableArray();
self.clearCurrentCompany = function() {
self.company(new BlankCompanyViewModel());
};
// Initialize the view-model
$.getJSON("/api/company", function(companies) {
$.each(companies, function(index, company) {
self.companies.push(new CompanyViewModel(company));
});
self.clearCurrentCompany();
});
}
Ideally I'd like to run ViewModel.clearCurrentCompany on the "Hidden" event of the modal like so:
$('#myModal').on('hidden', function() {
//Do something here, not sure what
});
I like to use a custom binding around a modal to make it open/close/display based on populating/clearing an observable.
Something like:
ko.bindingHandlers.modal = {
init: function(element, valueAccessor, allBindings, vm, context) {
var modal = valueAccessor();
//init the modal and make sure that we clear the observable no matter how the modal is closed
$(element).modal({ show: false, backdrop: 'static' }).on("hidden.bs.modal", function() {
if (ko.isWriteableObservable(modal)) {
modal(null);
}
});
//apply the template binding to this element
ko.applyBindingsToNode(element, { with: modal }, context);
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor) {
var data = ko.utils.unwrapObservable(valueAccessor());
//show or hide the modal depending on whether the associated data is populated
$(element).modal(data ? "show" : "hide");
}
};
You then use this against an observable. It acts like a with binding against that observable and shows/hides the modal based on whether the observable is populated.
Here is a sample that shows this in use and sets up a subscription where you could run custom code when the modal is closed. http://jsfiddle.net/rniemeyer/uf3DF/
function ViewModel() {
var self = this;
// your previous code
$('#myModal').on('hide', function() {
self.clearCurrentCompany();
});
}
Just like that. Note that you want hide, not hidden, because hidden fires only after the modal completely disappears. If a user opens a create before the previous view closes, it will still be populated.

How to remove and add a view using an if statement using backbone

I'm trying to remove my old carView and add the next one once the NEXT button is clicked.
Everything is coming out of a JSON file and is incrementing correctly but I want to view to also change.
Here's the code for my view:
window.CarContainerView = Backbone.View.extend({
el: $('#car-container'),
template:_.template($('#tpl-car-container').html()),
initialize:function () {
_.bindAll(this, 'clickNext');
this.car_number = 0;
this.car_model = this.model.get('carCollection').models[this.question_number];
this.question_view = null;
},
render:function () {
$(this.el).html(this.template());
this.car_view = new CarView({el: $(this.el).find('#car'), model: this.car_model});
this.question_view.render();
$('#next').bind('click', this.clickNext);
return this;
},
createNewCar: function () {
//build
console.log('createNewCar');
if(condition) {
//if the next button is pressed, clear screen and add new screen
}
},
clickNext: function () {
this.car_number++;
console.log(this.car_number);
createNewCar();
},
clickPrevious: function () {
}
});
Comments explain the changes. Basically, create a new CarView each time. And don't pass in the el to the view, else when you call remove that element will be gone. Instead, render the new view into #car each time.
window.CarContainerView = Backbone.View.extend({
el: $('#car-container'),
template:_.template($('#tpl-car-container').html()),
// use events hash instead of directly using jquery.
events: {
'click #next': 'clickNext'
},
initialize:function () {
// no need to use bindAll since using events hash
// binds the context of clickNext to this view already.
this.car_number = 0;
},
render:function () {
// use this.$el instead.
this.$el.html(this.template());
this.createNewCar();
return this;
},
createNewCar: function () {
if(this.car_view){
// cleanup old view.
this.car_view.remove();
}
// do some bounds checking here, or in clickNext... or both!
var car_model = this.model.get('carCollection').models[this.car_number];
// create a new view for the new car.
this.car_view = new CarView({model: car_model});
// render into #car instead of passing `el` into the view.
// let Backbone generate a div for the view, you dont need to
// set an `el` in the CarView either.
this.$('#car').html(this.car_view.render().el);
},
clickNext: function () {
this.car_number++;
this.createNewCar();
},
clickPrevious: function () {
}
});

Categories

Resources