Prototype-style of JQuery element observer - prototypejs

I need to replace old event listener code with a new, but without deleting old:
onchange="func1();func2();"
need to be replace by:
onchange="newFunc();func1();func2();"
Adding new code to element's onChange event via JQuery was simple:
var element = $('element');
var _onchange = element.onchange;
element.onchange = function() {
//some additional code
if (typeof(_onchange) == 'function') {
_onchange();
}
};
Now I need to rewrite it using Prototype.. I suppose it will be like:
element.observe('change', function() {
// new code here
// then old onChange
}.bindAsEventListener(element)));
How can I grab existing onChange's code?..

You actually don't need to .bindAsEventListener() except in rare cases
so adding the event observing to an element
$('element').observe('change',function(){
//onchange code
});
If you do this - it will add the new code as an observer without deleting any other observers setup for that element and event

Related

How to Include events (not event-plugin) in Ractive initialization/defaults?

I've read through the Ractive Documentation and I'm scratching my head a bit, because it seems like the default events initialization option allows me to do something - create new eventtypes - far more complex than what i need but conversely, there's no hook for the simpler, (more common?) task of defining default events
Could someone advise on how to provide global events that could be fired for traditional DOM events?
Example:
I have a 3 Component application page. I want to define a getOptions event, such that any <select on-click='getOptions'>...</select> will be handled by the same function. I don't want to have to define that function in each component.
My intuition would have been to do the following:
Ractive.events['getOptions'] = function(event){
//logic for getting the options for the value in event.keypath
}
or, if i wanted a true default that could be overridden...
Ractive.default.events['getOptions'] = function(event){
//logic for getting the options for the value in event.keypath
}
but my understanding of the documentation, is that Ractive.events and Ractive.default.events do not provide this, but rather provide a way to define new event plugins, that depend on a separate mechanism for getting fired:
Ractive.events.getoptions = function(node,fire){
//here goes logic for interacting with DOM event listeners, etc
}
//and then i would need to do this
ractive = Ractive.extend({...});
ractive.on('someOtherEventName',function(event){
//logic for getting the options for the value in event.keypath
});
//and then I could do this...
<select on-getoptions='someOtherEventName'>...</select>
but what would fire the getoptions in this case - from the template, rather than js ractive.fire()?
Would something like <select on-getoptions='someOtherFunction' on-click=getoptions>...</select> work? That seems very strange to me. Do I understand the concept correction? If not, what am i missing?
Is there a simple way to achieve the first example?
Ractive.events refers to custom events for mediating between the dom and the template:
Ractive.events.banana = function( node, fire ) { ... };
<div on-banana="doSomething()"/>
The handler for the event can either be the name of an event to fire, or a method on the component instance.
In your case, I think defining a method on the Ractive.prototype would be the best way to have a common handler:
Ractive.prototype.getOptions = function( /* pass in arguments */ ){
// and/or this.event will give you access
// to current event and thus context
// you can also override this method in components and
// call this base method using this._super(..)
}
// now any ractive instance can use:
<select on-click="getOptions(data)">...</select>
An event based approach usually entails letting the root instance or common parent in the view hierarchy handle same event across child components:
var app = new Ractive({
template: "<componentA/><componentB/>",
oninit(){
this.on( '*.getOptions', ( event, arg ) => {
// any child component (at any depth)
// that fires a "getOptions" event will
// end up here
});
}
});
// in component A or B:
<select on-click="getOptions">...</select>
UPDATE: If you wanted to assign an event handler to the prototype, so in essence every component is pre-wired to handle an event of a set name, you could do:
Ractive.prototype.oninit = function(){
this.on( 'getOptions', ( event ) => {
// handle any "getOptions" event that happens in the instance
});
}
Just be aware that you must call this._super(); in any component in which you also implement oninit:
var Component = Ractive.extend({
oninit() {
// make sure we call the base or event listener won't happen!
this._super();
// do this component instances init work...
}
}

Add or trigger event after inner content to page

I have links on a table to edit or delete elements, that elements can be filtered. I filtered and get the result using ajax and get functions. After that I added (display) the result on the table using inner.html, the issue here is that after filtering the links on the elements not work, cause a have the dojo function like this
dojo.ready(function(){
dojo.query(".delete-link").onclick(function(el){
var rowToDelete = dojo.attr(this,"name");
if(confirm("Really delete?")){
.......
}
});
I need to trigger the event after filtering, any idea?
(I'm assuming that you're using Dojo <= 1.5 here.)
The quick answer is that you need to extract the code in your dojo.ready into a separate function, and call that function at the end of your Ajax call's load() callback. For example, make a function like this:
var attachDeleteEvents = function()
dojo.query(".delete-link").onclick(function(el){
var rowToDelete = dojo.attr(this,"name");
if(confirm("Really delete?")){
.......
}
});
};
Then you call this function both in dojo.ready and when your Ajax call completes:
dojo.ready(function() { attachDeleteEvents(); });
....
var filter = function(someFilter) {
dojo.xhrGet({
url: "some/url.html?filter=someFilter",
handleAs: "text",
load: function(newRows) {
getTableBody().innerHTML = newRows;
attachDeleteEvents();
}
});
};
That was the quick answer. Another thing that you may want to look into is event delegation. What happens in the code above is that every row gets an onclick event handler. You could just as well have a single event handler on the table itself. That would mean there would be no need to reattach event handlers to the new rows when you filter the table.
In recent versions of Dojo, you could get some help from dojo/on - something along the lines of:
require(["dojo/on"], function(on) {
on(document.getElementById("theTableBody"), "a:click", function(evt) {...});
This would be a single event handler on the whole table body, but your event listener would only be called for clicks on the <a> element.
Because (I'm assuming) you're using 1.5 or below, you'll have to do it a bit differently. We'll still only get one event listener for the whole table body, but we have to make sure we only act on clicks on the <a> (or a child element) ourselves.
dojo.connect(tableBody, "click", function(evt) {
var a = null, name = null;
// Bubble up the DOM to find the actual link element (which
// has the data attribute), because the evt.target may be a
// child element (e.g. the span). We also guard against
// bubbling beyond the table body itself.
for(a = evt.target;
a != tableBody && a.nodeName !== "A";
a = a.parentNode);
name = dojo.attr(a, "data-yourapp-name");
if(name && confirm("Really delete " + name + "?")) {
alert("Will delete " + name);
}
});
Example: http://fiddle.jshell.net/qCZhs/1/

Edit button with comments using MooTools/AJAX

So I'm using a PHP API to interact with, to build a forum using MooTools. I can get comments from my database and add comments, but I want to inject an edit button to coincide with each comment.
I inject the comments using:
function domReady() {
$('newComment').addEvent('submit', addComment);
}
function addComment(e){
e.stop();
var req = new Request({
url:'control.php?action=insertPost',
onSuccess:addajaxSuccess
}).post(this);
}
function addajaxSuccess(idNo) {
new Element('span',{
'text':'Post successful.'
}).inject($(newComment));
$('commentList').empty();
domReady();
}
I want to attach an edit button to each comment injected, and add an event listener on the button to change the comment into a textarea for editting, with an update button.
Any ideas?
If you want to bind a global events to a dynamic content you have better look into Element Delegation In mootools.
Basically it's give you the ability to bind event to some container and "listen" to events of that children container base on selectors. I made you a little example here:
http://jsfiddle.net/xwpmv/
mainContainer.addEvents({
'click:relay(.mt-btn)': function (event, target) {
var btn = target;
if(btn.get('value') == 'Edit'){
btn.set('value','Done Editing');
var content = btn.getPrevious();
content.setStyle('display','none');
var textarea = new Element('textarea').set('text',content.get('text'));
textarea.inject(btn,'before');
}
else{
btn.set('value','Edit');
var textarea = btn.getPrevious();
var new_value = textarea.get('value');
textarea.destroy();
var content = btn.getPrevious();
content.set('text',new_value);
content.setStyle('display','block');
}
}
});
Here you can see the mainContainer listen to the click event of every element who has mt-btn class (the buttons)
You have several errors in your code but maybe it is just an example so I didn't relate to it.

Kendo UI dataSource changed event: is it working?

Is the dataSource.changed event working?
After my Kendo UI grid is instantiated, I am binding the change event per the documentation here:
http://docs.kendoui.com/api/framework/datasource#change
//To set after initialization
dataSource.bind("change", function(e) {
// handle event
});
I am doing this:
// initialize
$("#grid").kendoGrid({
dataSource: dataSource,
blah blah blah
)
});
// end of initialization
// bind afterwards
var grid = $('#grid').data('kendoGrid');
grid.dataSource.bind("change", function (e) {
dataChanged();
});
//also tried a setTimeout:
// bind afterwards
setTimeout(function () {
var grid = $('#grid').data('kendoGrid');
grid.dataSource.bind("change", function (e) {
dataChanged();
});
}, 350);
function dataChanged() {
// handle "change" whatever that means -- documentation definition is hazy
// does reassigning the data array constitute a change?
// does changing the value of a particular item in the data array
// constitute a change?
// does removing an item from the data array constitute a change?
var grid = $("#grid").data("kendoGrid");
grid.refresh();
}
But my dataChanged() function is not called when I do either of these things:
var grid = $('#grid').data('kendoGrid');
grid.dataSource.data()[1]["deptname"] = 'XXX';
or
grid.dataSource.data = aDifferentArray;
I am not sure exactly what the 'changed' event is listening for. What, precisely, is supposed to trigger it?
If I create a completely new dataSource, and assign it to the grid that already has a dataSource, I don't see how that would trigger an existing data source's changed event. Such an event (the grid noticing that its dataSource has been replaced with a different one) would be a grid-level event, not a dataSource-level event, right?
The important thing to note is that the data backing the DataSource is an ObservableArray, and that the data items in that array are converted to ObservableObjects.
The change event of the datasource is fired under 2 conditions:
The data ObservableArray changes (a record is inserted, deleted). An example of this would be using the DataSource.add() or DataSource.remove() functions.
If a property changed event bubbles up to the DataSource from one of the ObservableData objects in the array. However, just like the rest of the Kendo MVVM framework, the notification that a property changed only occurs when its .set("propertyName", value) function is called.
This is why grid.dataSource.data()[1]["deptname"] = 'XXX'; is not triggering the change event. If you change it to: grid.dataSource.data()[1].set("deptname", 'XXX'); then it should start to work. Basically, think of the change event as being fired in response to an MVVM property change fired from the data observable object.
As for changing the data array grid.dataSource.data = aDifferentArray; I'm actually not sure if that will or should trigger a change. I've never tried that.

How to bind events to element generated by ajax

I am using RenderPartial to generate CListView and all the contents generated properly and good pagination is working fine too. But when I added my custom JS to elements generated by the CListview it works fine for the the fist page content but when i use pagination and click to page 2 then the JS binding fails.
Is there any other way to bind custom event to elements generated in YII CListview I had tried using live, and on nothing work for me here is my js file.
I think I have to call my function on every ajax load in but how can I achieve in yii
This is the script I am using to update ratings on server with button click and this the element for which these forms and buttons are defined are generated by CListview in yii
$(document).ready(function(){
$('form[id^="rating_formup_"]').each(function() {
$(this).live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
});
You can also try CGridView.afterAjaxUpdate:
'afterAjaxUpdate' => 'js:applyEventHandlers'
The $.each method will loop only on existing elements, so the live binder will never see the ajax-generated content.
Why don't you try it like this:
$(document).ready(function(){
$('form[id^="rating_formup_"]').live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
This problem can be solved by two ways:
Use 'onclick' html definitions for every item that is going to receive that event, and when generating the element, pass the id of the $data to the js function. For example, inside the 'view' page:
echo CHtml::htmlButton('click me', array('onclick'=>'myFunction('.$data->id.')');
Bind event handlers to 'body' as the framework does. They'll survive after ajax updates:
$('body').on('click','#myUniqueId',funcion(){...});

Resources