Callback for when a child dom element is inserted or has its class changed? - callback

In Ember.js, I have a view that has
{{#if obj.property}}
<div {{bindAttr class="prop"}}>content</div>
{{/if}}
How can I get called back for when this element is inserted into the view, and for when the class is attached onto the element? I want to do this because the CSS class is an animation class, and I'd like to hook onto the onAnimationEnd event of the element so that I get notified when the animation ends.

How about changing the div to be a custom view subclass that implements didInsertElement? e.g.
{{#if obj.property}}
{{view App.MyView}}
{{/if}}
and
App.MyView = Ember.View.extend({
classNameBindings: "prop",
didInsertElement: function() {
// use this.$() to get a jQuery handle for the element and do what you'd like
}
})

In addition to Luke's answer, I found out another way to achieve this, which may be preferable since creating a view is required for Luke's approach.
By exploiting the fact that DOM events bubble up, I can setup an event handler for animationEnd on a parent DOM element that contains whatever may be inserted. E.g.
<div id="container">
{{#if obj.property}}
<div {{bindAttr class="prop"}}>content</div>
{{/if}}
</div>
// view.js
didInsertElment: function() {
this.$('#container').bind('webkitAnimationEnd', function(e) {
// e.target is the element whose animation ended.
}
}

Related

Reactjs together with TinyMCE editor code plugin

I'm using Reactjs together with the tinyMCE 4.1.10 html editor (together with the code plugin) and bootsrap css + js elements. A fairly working setup after a few quirks with the editor have been removed (manual destruction if the parent element unmounts)
Now the question: The textarea input of the code plugin does not receive any focus, click or key events and is basically dissabled. Setting the value via javascript works just fine, but it does not function as a normal html input.
It is opened as the following:
datatable as react components
opens bootsrap modal as react component
initializes tinymce on textareas inside of the modal
loads the code plugin (which itself then is not accepting any kind of input anymore)
My initilization of the editor looks like this:
componentDidMount: function(){
tinymce.init({
selector: '.widget-tinymce'
, height : 200
, resize : true
, plugins : 'code'
})
}
My guess would be, that react.js is somehow blocking or intersepting the events here. If I remove the react modal DOM, it is just working fine.
Does anybody has an idea, what is causing this or how to simply debug it further?
Thx a lot!
if you are using Material UI. disable Material UI Dialog's enforce focus by adding a prop disableEnforceFocus={true} and optionally disableAutoFocus={ true}
What does your html/jsx look like in your component?
My guess is that react might be treating your input as a Controlled Component
If you're setting the value attribute when you render, you'll want to wait, and do that via props or state instead.
Alright, so it turned out that bootstrap modals javascript is somehow highjacking this. In favor of saving some time I decided not to dig realy into this but just to create my own modal js inside of the jsx.
Aparently there is also React Bootstrap, but it looks at the moment to much beta for me in order to take this additional dependency in.
The final code looks like this, in case it becomes handy at some point:
Modal = React.createClass({
show: function() {
appBody.addClass('modal-open');
$(this.getDOMNode()).css('opacity', 0).show().scrollTop(0).animate({opacity: 1}, 500);
}
, hide: function(e){
if (e) e.stopPropagation();
if (!e || $(e.target).data('close') == true) {
appBody.removeClass('modal-open');
$(this.getDOMNode()).animate({opacity: 0}, 300, function(){
$(this).hide();
});
}
}
, showLoading: function(){
this.refs.loader.show();
}
, hideLoading: function(){
this.refs.loader.hide();
}
, render: function() {
return (
<div className="modal overlay" tabIndex="-1" role="dialog" data-close="true" onClick={this.hide}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" onClick={this.hide} data-close="true" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title" id="myModalLabel">{this.props.title}</h4>
</div>
<div className="modal-body" id="overlay-body">
{this.props.children}
<AjaxLoader ref="loader"/>
</div>
</div>
</div>
</div>
);
}
})
Best wishes
Andreas
Material UI: disable Dialog's enforce focus by adding a prop disableEnforceFocus={true} and optionally disableAutoFocus={ true}

How to reach _id of document when it's in the parent data context?

This seems like an open-and-shut case for Template.parentData(), but to this day I've never once managed to get that bad boy working properly.
What I want is an event that updates a document depending on which button was clicked, but the buttons are themselves dependent on an array buried deeper in the document, where the _id doesn't exist.
Here's what I have:
First, a helper that sets the context peopleList:
Template.people.helpers({
peopleList: function() {
return People.find()
}
Which I use to iterate through in the HTML, printing out the first and last name of each person stored in the database, as well as their favorite colors (extraneous markup removed):
{{#each peopleList}}
<li>
{{firstName}} {{lastName}}
{{#each favoriteColors}} <button>{{this}}</button> {{/each}}
</li>
{{/each}}
It should be noted at this point that favoriteColors is a key inside the document which holds an array. So the whole thing looks something like this:
{
firstName: "Johnny",
lastName: "Boy",
favoriteColors: ["red", "blue", "blanchedAlmond"]
}
Imagine now that I want to be able to press any of these buttons, which hold the favorite colors, to set the, uh, super-duper favorite color or something. So a button click on blanchedAlmond should update the document, adding the key masterColor with the value blanchedAlmond.
The event:
'click button': function() {
var masterColor = ????
var docId = ????
Meteor.call('setMasterColor', masterColor, docId)
}
I could provide HTML data-tags that hold the color value (because this inside the event spits out some weird array with each letter separated for some reason) and even the _id with {{../_id}}, but that feels like cheating, and I really want to learn how to do the same thing inside a helper or an event.
I strongly feel like this would be a case for Template.parentData() but it returns nothing at all when I console.dir it. What should I do?
The confusion around parentData has to do with the event context. The event is attached to the template whose context is something that isn't a person or a color. Whenever you get the feeling that you need to start littering your code with data- attributes, the answer is nearly always to add more templates. For example:
html
<template name="myTemplate">
<ul>
{{#each peopleList}}
{{> person}}
{{/each}}
</ul>
</template>
<template name="person">
<li>
{{firstName}} {{lastName}}
{{#each favoriteColors}}
{{> color}}
{{/each}}
</li>
</template>
<template name="color">
<button>{{this}}</button>
</template>
js
Template.color.events({
'click button': function() {
// this context is a color - remember to convert it to a string
var masterColor = String(this);
// the parent context is a person
var docId = Template.parentData(1)._id;
return Meteor.call('setMasterColor', masterColor, docId);
}
});

knockout multiple viewmodels in a page not working

i have two seperate viewmodels in a page
function AModel() {
...
}
function BModel() {
...
self.testValue= ko.observable('test')
}
$(document).ready(function() {
var AModel1= new AModel();
var BModel1= new BModel();
ko.applyBindings(AModel1);
ko.applyBindings(BModel1);
});
now in html page
how do i make it work?
<span data-bind="text: BModel1.testValue" ></span>
You should not call ko.applyBindings multiple times on the same DOM element, this can lead to problems or to an exceptions since KO 2.3.
What you can do is to create one "wrapper" viewmodel and call ko.applyBindings with it:
$(document).ready(function() {
var AModel1= new AModel();
var BModel1= new BModel();
ko.applyBindings({ AModel1: AModel1, BModel1: BModel1 });
});
Then you can use your view:
<span data-bind="text: BModel1.testValue" ></span>
Demo JSFiddle.

Jquery Accordion choosing correct selector

I'm struggling with plugging in the correct selector into jquery. When I plug in ".accordionButton" the entire div is clickable and the functionality works great. However, I want to make only the "h3.toggle a" clickable, but plugging that selector in doesn't work. Is there something else in the jquery I need to change here? Any advice is greatly appreciated. Thanks!
The HTML:
<div class="accordionButton">
<div class="case-top">
<div class="case-left"></div>
<div class="case-right">
<h3 class="toggle">Our Strategy and Results</h3>
</div>
</div><!--end case-top-->
</div><!--end button-->
<div class="accordionContent">sliding content here</div>
The JQUERY:
$(document).ready(function() {
//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
$('.accordionButton h3.toggle a').click(function() {
//REMOVE THE ON CLASS FROM ALL BUTTONS
$('.accordionButton h3.toggle a').removeClass('on');
//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
$('.accordionContent').slideUp('normal');
//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
if($(this).next().is(':hidden') == true) {
//ADD THE ON CLASS TO THE BUTTON
$(this).addClass('on');
//OPEN THE SLIDE
$(this).next().slideDown('normal');
}
});
/*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/
//ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER
$('.accordionButton h3.toggle a').mouseover(function() {
$(this).addClass('over');
//ON MOUSEOUT REMOVE THE OVER CLASS
}).mouseout(function() {
$(this).removeClass('over');
});
$('.accordionContent').hide();
});
You are using
$(this)
but you change the selector, you need to change all $(this) selectors to
$('.accordionButton')
FIDDLE
Ok, here is where I'm at... the buttons are now working correctly, but on click all the instances of .accordionContent open, not just next one. ( FYI, I removed the mouseover from this code snipped)
Jquery
$(document).ready(function() {
//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
$('.accordionButton h3.toggle a').click(function() {
//REMOVE THE ON CLASS FROM ALL BUTTONS
$('.accordionButton h3.toggle a').removeClass('on');
//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
$('.accordionContent').slideUp('normal');
//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
if($('.accordionButton').next().is(':hidden') == true) {
//ADD THE ON CLASS TO THE BUTTON (correct)
$(this).addClass('on');
//OPEN THE SLIDE
$('.accordionButton').next().slideDown('normal');
}
});
I'm guessing the lines:
$('.accordionButton').next().slideDown('normal');
and
if($('.accordionButton').next().is(':hidden') == true) {
are the lines which need editing. I need these two lines to open and close just the "next" .accordionContent instances not all of the instances together.

Unbind view model from view in knockout

I'm looking for unbind functionality in knockout. Unfortunately googling and looking through questions asked here didn't give me any useful information on the topic.
I will provide an example to illustrate what kind of functionality is required.
Lets say i have a form with several inputs.
Also i have a view model binded to this form.
For some reason as a reaction on user action i need to unbind my view model from the form, i.e. since the action is done i want all my observables to stop reacting on changes of corresponding values and vise versa - any changes done to observables shouldn't affect values of inputs.
What is the best way to achieve this?
You can use ko.cleanNode to remove the bindings. You can apply this to specific DOM elements or higher level DOM containers (eg. the entire form).
See http://jsfiddle.net/KRyXR/157/ for an example.
#Mark Robinson answer is correct.
Nevertheless, using Mark answer I did the following, which you may find useful.
// get the DOM element
var element = $('div.searchRestults')[0];
//call clean node, kind of unbind
ko.cleanNode(element);
//apply the binding again
ko.applyBindings(searchResultViewModel, element);
<html>
<head>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript" src="knockout-2.2.1.js"></script>
<script type="text/javascript" src="knockout-2.2.1.debug.js"></script>
<script type="text/javascript" src="clickHandler.js"></script>
</head>
<body>
<div class="modelBody">
<div class = 'modelData'>
<span class="nameField" data-bind="text: name"></span>
<span class="idField" data-bind="text: id"></span>
<span class="lengthField" data-bind="text: length"></span>
</div>
<button type='button' class="modelData1" data-bind="click:showModelData.bind($data, 'model1')">show Model Data1</button>
<button type='button' class="modelData2" data-bind="click:showModelData.bind($data, 'model2')">show Model Data2</button>
<button type='button' class="modelData3" data-bind="click:showModelData.bind($data, 'model3')">show Model Data3</button>
</div>
</body>
</html>
#Mark Robinson gave perfect solution, I've similar problem with single dom element and updating different view models on this single dom element.
Each view model has a click event, when click happened everytime click method of each view model is getting called which resulted in unnecessary code blocks execution during click event.
I followed #Mark Robinson approach to clean the Node before apply my actual bindings, it really worked well.
Thanks Robin.
My sample code goes like this.
function viewModel(name, id, length){
var self = this;
self.name = name;
self.id = id;
self.length = length;
}
viewModel.prototype = {
showModelData: function(data){
console.log('selected model is ' + data);
if(data=='model1'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel1, button1[0]);
console.log(viewModel1);
}
else if(data=='model2'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel3, button1[0]);
console.log(viewModel2);
}
else if(data=='model3'){
ko.cleanNode(button1[0]);
ko.applyBindings(viewModel3, button1[0]);
console.log(viewModel3);
}
}
}
$(document).ready(function(){
button1 = $(".modelBody");
viewModel1 = new viewModel('TextField', '111', 32);
viewModel2 = new viewModel('FloatField', '222', 64);
viewModel3 = new viewModel('LongIntField', '333', 108);
ko.applyBindings(viewModel1, button1[0]);
});