How do I know when component's DOM is updated and finished transitions in Ractive? - custom-component

I'm trying to wrap IScroll library into Ractive component. Is there a way to be notified when component's DOM changed and finished any transitions so that I can update the scroller? I see the following ways to achieve this:
Declare dependencies (of the component's template) explicitly, like
<Scroll context="{{...}}" > </Scroll>
I can observe context variable, but still can't wait for transitions to finish.
Patch Ractive.set() so that it emits custom event when used:
// Broadcast promise returned by `set`.
var oldset = Ractive.prototype.set;
Ractive.prototype.set = function () {
var ret = oldset.apply(this, arguments);
this.fire('set', ret);
return ret;
};
Then, in the component's initialization code, I can subscribe to the set event:
this._parent.on('set', function (ret){
ret.then(update);
});
This will not work for Ractive.push() and other methods. Also this will notify my component about all changes made by set-ting something, not only about those affecting component's DOM. Finally, I must explicitly refer to component's parent using this._parent, which means my components can not be nested.
So, is there are better way to achieve this in Ractive?

The initialization options allow oncomplete (or ractive.on('complete'... if you prefer) for initial render. See http://docs.ractivejs.org/latest/lifecycle-events
All of the data modification methods, set, animate, push, slice, etc. return a promise that will not be called until DOM is updated and transitions have completed.
Here's a simple example (http://jsfiddle.net/ctfyes7t/):
{{#if show}}
<li intro='fade:{ duration: 2000 }'>ta da!</li>
{{/if}}
r.set('show', true).then(function(){
// called when fade intro complete
});

The problem can be approached from another direction: changes to the specific parts of DOM can be observed using MutationObserver.
So, I end up with the following approach to wrapping external widgets:
basically, we get component's top node (and initialize 3rd party code) using intro transition, and then in oncomplete callback register observer with something like this:
this.observer = new MutationObserver(update);
this.observer.observe(this.node, {
childList: true,
subtree: true,
characterData: true,
attributes: true, // transitions may change attributes
});
where function update updates 3rd-party widget.
Here is the source code of the component.

Related

Using jquery-ias with async-loaded content

I've somewhat successfully integrated the jQuery Infinite Ajax Scroll plugin into my development site - it is used twice, first on the thread list on the left, second when you load up an individual topic - but I'm having trouble with the second ias instance here.
Basically the content of a topic is loaded via $.get and then rendered into the page, and then I trigger setupThreadDetailDownwardScroll() in JS which creates an instance of ias:
var iasDetail = jQuery.ias({
container: "#reply-holder",
item: ".post",
pagination: ".threaddetail-pagination",
next: ".load-next-inner-link a",
delay: 2000,
});
if (iasDetail.extension) {
iasDetail.extension(new IASPagingExtension());
iasDetail.extension(new IASTriggerExtension({
text: 'More Replies',
html: '<div class="scroll-pager"><span>{text}</span></div>',
offset: 10,
}));
iasDetail.extension(new IASNoneLeftExtension({html: '<div class="scroll-message"><span>No more replies</span></div>'}));
iasDetail.extension(new IASHistoryExtension({
prev: '.load-previous-inner-link a',
}));
}
iasDetail.on('load', function() {
$('#reply-holder').append(scrollLoading);
})
iasDetail.on('rendered', function() {
$('.scroll-loading').remove();
iasDetail.unbind();
})
But the problem is that this only works with whatever the first topic you load is - you'll get working pagination in the first thread, but then it'll fallback to anchor links when you open the next thread.
So I figured that I needed to rebind ias once this new content is inserted, and this is why I have added the unbind() call in rendered, and then I re-call setupThreadDetailDownwardScroll() whenever another thread is loaded. This doesn't work either though.
Is there a correct procedure here?
You are using jQuery.ias(...) which binds to the scroll event of $(window). In your case you probably want to bind to an overflow div. Therefor you should specify the scrollContainer like this:
$('#scrollContainer').ias(...)
Edit:
Based on you comment I took another look at it and might have found an answer. When you call jQuery.ias({...}); IAS gets setup and waits for $(document).ready to initialize. You say you want to initialize IAS in your setupThreadDetailDownwardScroll function. You can try to initialize IAS yourself with the following code
iasDetail.initialize();

Google Dart: change event for IListElement

I'm wondering if you can listen for when the elements of a UListElement has changed (i.e. LIElement added or removed)?
UListElement toDoList = query('#to-do-list');
LIElement newToDo = new LIElement();
newToDo.text = "New Task";
toDoList.elements.add(newToDo);
// how do I execute some code once the newToDo has been added to the toDoList?
I'm assuming elements.add() is asynchronous as I come from an ActionScript background. Is this a valid assumption?
Higher level frameworks give you events for this, but at the HTML5 API level, you have to use a MutationObserver.
Here's an example where a mutation observer can be set on any DOM Element object. The handler can then process the mutation events as needed.
void setMutationObserver(Element element){
new MutationObserver(mutationHandler)
.observe(element, subtree: true, childList: true, attributes: false);
}
void mutationHandler(List<MutationRecord> mutations,
MutationObserver observer){
for (final MutationRecord r in mutations){
r.addedNodes.forEach((node){
// do stuff here
});
r.removedNodes.forEach((node){
// or here
});
}
}
element.elements.add(otherElement) is synchronous and is the equivalent of element.appendChild(otherElement) in Javascript (ie. DOM Level 2 Core : appendChild).
You may also be interested in our work with MDV:
http://blog.sethladd.com/2012/11/your-first-input-field-binding-with-web.html
http://blog.sethladd.com/2012/11/your-first-model-driven-view-with-dart.html

In ember, how do I pass view data from a drag into a drop?

I'm using ember latest and jquery.ui's Draggable and Droppable. I am also using some mixins that a talented ember person created to make a Draggable and Droppable view in ember. Here's the fiddle:
http://jsfiddle.net/inconduit/6n49N/7/
I need to attach the view's content to the drag event so that I can access it in the drop event. With straight up jquery, I know you'd do $(..).draggable({ .. }).data("myData","some data here"); but I don't know how to reference the view's content in this ember implementation.
Here's a snippet from App.Draggable in the fiddle:
App.Draggable = JQ.Draggable.extend({
appendTo: 'body',
helper: function() {
$(this).data("myData","this is where actual data would go");
JQ.Draggable extends Ember.View. Inside the helper() function, 'this' refers to the actual DOM element, I don't know how to refer to the View's variables. I want to pass the view's content so that it can be retrieved here:
App.Droppable = JQ.Droppable.extend({
drop: function(event,ui) {
alert('Dropped! ' + $(ui.draggable).data("myData"));
The template for the draggable looks like this:
{{#view App.Draggable contentBinding="App.anObject"}}Drag me{{/view}}
and I would like to pass that content. Please have a look at the fiddle, the pertinent functions are defined at the bottom of the javascript.
answering my own question here.
i attached the data in the didInsertElement callback as follows:
App.DraggableDataView = App.Draggable.extend({
didInsertElement: function() {
this._super();
var element = this.get('element');
$(element).data('myData',this.get('content'));
},
});

Create jQuery ui resizable instance using selector added to DOM by jQuery

I'm trying to start a jquery ui resizable instance, but using a selector added to the DOM by jquery itself. This is a basic example of my script:
HTML:
<div class='lyr'></div>
jQuery:
// Add class
$('lyr').addClass('fixed');
// Resizable
$('.fixed').resizable({
aspectRatio: true,
handles: 'all'
});
I've thought about using something along the lines of live() or bind() but I have no event to bind to. Any help appreciated.
I have used the LiveQuery plugin - http://brandonaaron.net/code/livequery/docs in the past to be able to target elements added to the dom, like in your case.
If I've got this right, you want anything on the page which has the class "fixed" to be resizable, even if the class is added after the page has loaded? You're right that live, bind and delegate won't help here.
I can think of two possibilities, neither lovely.
First, set up a live "mouseenter" event which will make the element resizable if it wasn't before:
$(body).delegate(".fixed", "mouseenter", function(ev) {
var target = $(ev.target);
if (target.data("resizable")) return;
target.resizable({
aspectRatio: true,
handles: 'all'
});
})
This gets us round the problem of having no event to bind to.
Alternatively, you could monkeypatch jQuery.fn.addClass:
var classRe = new RegExp(c + className + \b);
._addClass = jQuery.fn.addClass;
jQuery.fn.addClass = function(className) {
if (classRe.test(classname)) {
if (this.data("resizable")) return;
this.resizable({
aspectRatio: true,
handles: 'all'
});
}
jQuery.fn._addClass.apply(this, arguments);
}
Of course this will only work if the class is added through the addClass method.
Also in your example,
$('lyr').addClass('fixed');
Should probably be:
$('.lyr').addClass('fixed');

jQuery live with the ready or load event

I'm using the jQuery Tools tooltip plugin, which is initialized with $('selector').tooltip(). I'd like to call this on any current or future .tooltipper element. I figured that the following would work:
$('.tooltipper').live('ready', function(){
$(this).tooltip()
}
But it was unsuccessful---the ready event did not fire. The same for load. I've read that livequery can produce the result of I'm looking for, but surely there is a way to use jQuery .live() to pull it off, considering the documentation says that it works for all jQuery events, of which I believe ready is one.
Quoted from the jQ API (http://api.jquery.com/live/):
In jQuery 1.3.x only the following JavaScript events (in addition to custom events) could be bound with .live(): click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.
As of jQuery 1.4 the .live() method supports custom events as well as all JavaScript events.
As of jQuery 1.4.1 even focus and blur work with live (mapping to the more appropriate, bubbling, events focusin and focusout).
As of jQuery 1.4.1 the hover event can be specified (mapping to "mouseenter mouseleave").
.live() does not appear to support the ready event.
To add to HurnsMobile's excellent answer; Looking at bindReady(), which is the internal call that jQuery makes to bind to the document load event every time you call $(some_function) or $(document).ready(some_function) we see why we cannot bind to "ready":
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
return jQuery.ready();
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) { //and silently drop any errors
}
// If the document supports the scroll check and we're not in a frame:
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
}
To sum it up, $(some_function) calls a function which binds to:
DOMContentLoaded
onreadystatechange (DOMContentLoaded)
window.load / onload
Your best bet would be to bind to those actions that might create new .tooltipper elements, rather than trying to listen for the ready event (which happens only once).
HurnsMobile is right. JQuery live does not support the ready-event.
This is why I created a plugin that combines the two. You register your callback once, and then you will need to call the plugin once for content you add manually.
$.liveReady('.tooltipper', function(){
this.tooltip()
});
Then when creating new content:
element.html(somehtml);
element.liveReady();
or
$('<div class="tooltipper">...').appendTo($('body')).liveReady();
A demo is available here: http://cdn.bitbucket.org/larscorneliussen/jquery.liveready/downloads/demo.html
Check out the introductory post here: http://startbigthinksmall.wordpress.com/2011/04/20/announcing-jquery-live-ready-1-0-release/
Also have a look at http://docs.jquery.com/Plugins/livequery, which listenes for changes on the dom.