I can't create a class based on actual HTML element - javascript

I'm trying to create a simple gallery with prototype.js and script.aculo.us. To handle left and right arrow I made this code, but it doesn't work
Gallery.Arrow = Class.create(document.createElement('a'), {
initialize: function(listener) {
this.on('click', listener);
this.addClassName('xjsl-arrow');
}
});
this.on is undefined. I tryed Class.create($(document.createElement('a')), ..., or even Element.extend(this) in the initialize function, but nothing works.
If I tryed Event.Handler(this, 'click', listener) to, but the error come from element.attachEvent inside prototype.js library.
Is it possible to create a class based on HTML element ?

Try building the Class based on the Element.Methods namespace like this
Gallery.Arrow = Class.create(Element.Methods, {
initialize: function(element,listener) {
this.on(element,'click', listener);
this.addClassName(element,'xjsl-arrow');
}
});
jsfiddle example http://jsfiddle.net/rPLa8/

Related

Trigger view event with jQuery

I have a Backbone View with simple events:
Backbone.View.extend({
events: {
"change #id": "idChanged"
},
idChanged: function () {}
initialize: function () {
/* construct HTML */
$("#id").trigger("change");
}
});
However this does not fire the idChanged event. When I change #id with the browser it does fire. How can I trigger the Backbone View event?
a couple of things in your code.
1 I don't think you defined your events correctly.
It should be a hash, or a function that returns a hash, like so:
events: {
"change #id": "idChanged"
}
2 a few typos like "function" and missing comma
then, to make the events work, the defined #id element must be inside the view's el. If the element is outside of the view, it's not gonna work.
also, you cannot trigger that in initialize, because before that function is executed, the view is not fully initialized yet. :)
here's a working example:
http://jsfiddle.net/3KmzQ/
That's because the events hash will be bound to the view when it gets rendered, which happens after the initialize code gets run. Try calling the desired callback directly:
Backbone.View.extend({
events: function () {
"change #id": "idChanged"
},
idChanged: function () {}
initialize: function () {
/* construct HTML */
this.idChanged();
}
});
You used "extend".
Same code should apply to Backbone.view.Object( {....} )
Specify the object that you would like to fire events at.
Backbone.View.Ojbect(
{
events: function () {
"change #id": "idChanged"
},
idChanged: funciton () {}
initialize: function () {
/* construct HTML */
$("#id").trigger("change");
}
}
);
That is, try not to extend.

durandaljs - how to query a DOM element from a widget after ready

I want to query a element in a durandaljs widget, when it's ready.
If i use the selector directly in the data-binding, the element will not be found:
html (no attached view):
<button id="myButton"></button>
<div data-bind="widget: { kind: 'myWidget', options: { btn: $('#myButton') } }"></div>
controller.js:
define(function (require) {
var ctor = function (element, settings) {
var btn = settings.options.btn;
// btn = $('#myButton'); // this will work, but i'm not sure if the DOM is
// currently ready in the constructor
btn.on("click", function () {
console.log("I want to be fired");
});
};
return ctor;
});
Whats the best way to query a DOM element from a durandal widget at start?
I'm not sure where the html fragment belongs to so there are two slightly different answers.
First I'd suggest that you don't pass in the btnas jQuery object ({btn: $('myButton')}) , when you're not sure that it already exists. It's probably better to pass in a selector {btn: '#myButton'} and let the widget figure out how to deal with it.
Does your widget have its own view.html and the button is defined inside? If that's the case than you should take a look at the viewAttached callback.
var ctor = function (element, settings) {
this.btn = settings.options.btn;
};
ctor.prototype.viewAttached = function (view){
var btn = $(this.btn, view);
if ( btn.length > 0 ) {
btn.on("click", function () {
console.log("I want to be fired");
});
}
}
If your widget doesn't have its own view.html than you should let the widget know by adding a view property to the settings object with a value of false.
Here's the paragraph from http://durandaljs.com/documentation/Creating-A-Widget/ that explains that.
Note: In some cases, your widget may not actually need a view. Perhaps it's just adding some jQuery behavior or applying an existing jQuery plugin to a dom element. To tell Durandal that there is no view to load and bind, add a view property to the settings object with a value of false inside your widget's constructor.
In that instance however you can only access elements that are already in the DOM when the widget is instantiated e.g.
var ctor = function (element, settings) {
settings.view = false;
this.btn = $(settings.options.btn);
if ( this.btn.length > 0 ) {
this.btn.on("click", function () {
console.log("I want to be fired");
});
}
};

Creating a custom widget in Dojo, error calling functions within the new widget?

The issue is i am following the tutorial here and the functionality of the new widget work fine until i hover over the widget where a this._changeBackground method is being called from "on" listeners, i get the error TypeError: this._changeBackground is not a function
The final code as implemented from tutorial looks like this:
define(["dojo/_base/declare","dijit/_WidgetBase", "dijit/_TemplatedMixin", "dojo/text!/JS/Allatus/Test.html", "dojo/dom-style", "dojo/_base/fx", "dojo/_base/lang","dojo/on"],
function(declare, WidgetBase, TemplatedMixin, template, domStyle, baseFx, lang , on){
return declare([WidgetBase, TemplatedMixin], {
// Some default values for our author
// These typically map to whatever you're handing into the constructor
name: "No Name",
// Using require.toUrl, we can get a path to our AuthorWidget's space
// and we want to have a default avatar, just in case
avatar: require.toUrl("JS/Allatus/custom/android_vector.jpg"),
bio: "",
// Our template - important!
templateString: template,
// A class to be applied to the root node in our template
baseClass: "authorWidget",
// A reference to our background animation
mouseAnim: null,
// Colors for our background animation
baseBackgroundColor: "#fff",
mouseBackgroundColor: "#def",
postCreate: function(){
// Get a DOM node reference for the root of our widget
var domNode = this.domNode;
// Run any parent postCreate processes - can be done at any point
this.inherited(arguments);
// Set our DOM node's background color to white -
// smoothes out the mouseenter/leave event animations
domStyle.set(domNode, "backgroundColor", this.baseBackgroundColor);
// Set up our mouseenter/leave events - using dojo/on
// means that our callback will execute with `this` set to our widget
on(domNode, "mouseenter", function (e) {
this._changeBackground(this.mouseBackgroundColor);
});
on(domNode, "mouseleave", function (e) {
this._changeBackground(this.baseBackgroundColor);
});
},
_changeBackground: function(toCol) {
// If we have an animation, stop it
if (this.mouseAnim) { this.mouseAnim.stop(); }
// Set up the new animation
this.mouseAnim = baseFx.animateProperty({
node: this.domNode,
properties: {
backgroundColor: toCol
},
onEnd: lang.hitch(this, function() {
// Clean up our mouseAnim property
this.mouseAnim = null;
})
}).play();
},
_setAvatarAttr: function(av) {
// We only want to set it if it's a non-empty string
if (av != "") {
// Save it on our widget instance - note that
// we're using _set, to support anyone using
// our widget's Watch functionality, to watch values change
this._set("avatar", av);
// Using our avatarNode attach point, set its src value
this.avatarNode.src = av;
}
}
});
});
Any Ideas Why I cant call another function within my customize widget ? is that just a bug or i am doing something wrong?
Your mouseEnter function is being called outside the scope of your widget (scope in JS refers to the value of the "this" variable). This is a common problem and dojo has a simple solution, the function lang.hitch can be used to tie a function to a certain scope. (and more, I would recommending reading the docs on it). Here's how you should use it in this scenario :
// Set up our mouseenter/leave events - using dojo/on
// means that our callback will execute with `this` set to our widget
on(domNode, "mouseenter", lang.hitch(this, function (e) {
this._changeBackground(this.mouseBackgroundColor);
}));
on(domNode, "mouseleave", lang.hitch(this, function (e) {
this._changeBackground(this.baseBackgroundColor);
}));
The scope of this by default in on callbacks is window. Since you want the scope to be the widget itself, you need to import dojo/_base/lang and use the lang#hitch function to explicitly set the scope of the callback
on(domNode, "mouseenter", lang.hitch(this,function (e) {
this._changeBackground(this.mouseBackgroundColor);
}));
on(domNode, "mouseleave", lang.hitch(this,function (e) {
this._changeBackground(this.baseBackgroundColor);
}));

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});

Using variable for selectors in events

for some reason I need to use a variable as the selector for events in backbone, but I can't figure how to do this :
app.views.Selfcare = Backbone.View.extend({
events: {
click window.parent.document .close : "closeWindow"
},
closeWindow: function() {
//code
}
});
I have to use a different scope and I can't do "click .close" : "closeWindow".
Thx for your help.
I had a look at Backbone.js's source code and found out that if your view's events is a function then the function is called and it's return value is used as the events object.
This means that your code can be changed like this:
app.views.Selfcare = Backbone.View.extend({
events: function() {
var _events = {
// all "standard" events can be here if you like
}
_events["events" + "with variables"] = "closeWindow";
return _events;
},
closeWindow: function() {
//code
}
});
THIS is the interesting part of the source code:
if (_.isFunction(events)) events = events.call(this);
Update:
Example is available on JSFiddle HERE**
I'm not sure that you'll be able to use a variable there. You could use the built-in Events methods (see documentation) to add a custom listener, then add an event listener to window.parent.document to trigger that custom event (use the Events.trigger method).
That said, it would be much easier to decouple this event from Backbone entirely (unless you don't want to do that), and go down the addEventListener route:
app.views.Selfcare = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'closeWindow');
if(this.options.clickTarget) {
this.options.clickTarget.addEventListener('click', this.closeWindow, false);
}
},
render: function() {
// Render to the DOM here
return this; // as per Backbone conventions
},
closeWindow: function() {
// Stuff here
}
});
// Usage:
var mySelfcare = new app.views.Selfcare({
clickTarget: window.parent.document
});
I think that should work, although I haven't tested it (and there may be one or two syntactical errors!)

Categories