Selectize.js events - wont work - javascript

I need some help with selectize.js events - they dont work...
Inicialize selectize.js:
$("input[name='addTask[users]']").selectize({
valueField: 'email',
labelField: 'name',
//... more options like render...
});
And setting event:
$("input[name='addTask[users]']").selectize().on('type', function(){
alert();
});
If I typing in input nothing happens...
EDIT: No errors in console, selector is good because plugin works perfectly.
Only one event is working for me - "change".
Here si documentation:https://github.com/brianreavis/selectize.js/blob/master/docs/events.md
(Also I do not understand "params" - on what the needs are and what they do)
Any hints, ideas? Examlple it pleases me...
EDIT: OK I GOT IT!!! SO - SOLUTION:
In initialization selectize.js:
$("input[name='addTask[users]']").selectize({
valueField: 'email',
labelField: 'name',
onType : eventHandler('onType'), // <----- this added
//... more options like render...
});
and BEFORE initialization:
var eventHandler = function(name) {
return function() {
alert(name + ' ' + arguments['0']); // name of event + typed string
};
};
And alert work if you start typing in input :)

Your issue is in this line:
$("input[name='addTask[users]']").selectize().on('type', function(){
alert();
});
You should have done:
$("input[name='addTask[users]']")[0].selectize.on('type', function(){
alert();
});
From the Docs: When initializing the control, the "selectize" property is added on the original / element—this property points to the underlying Selectize instance.
// initialize the selectize control
var $select = $('select').selectize(options);
// fetch the instance
var selectize = $select[0].selectize;
And Event Docs:
Selectize instances have a basic event emitter interface that mimics jQuery, Backbone.js, et al:
var handler = function() { /* ... */ };
selectize.on('event_name', handler);
selectize.off('event_name');
selectize.off('event_name', handler);

Related

Unable to catch CKEditor change event

I looked through many threads at SO, but could not find an answer that solves my problem. So, I define a CKEditor instance like so:
var editor = $('#test-editor');
editor.ckeditor(function() {}, {
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
However I do not know how can I catch change event. This is what I tried:
var t = editor.ckeditor(function() {
this.on('change', function () {
console.log("test 1");
});
}, {
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
editor.on('change', function() {
console.log("test 2");
});
t.on('change', function() {
console.log("test 3");
});
All these three attempts ended in failure. I should add, that I do not want to loop through all editors on a page, I just want to address one particular editor rendered at component with #test-editor. How can I do that?
The jQuery ckeditor() method returns a jQuery object, which exposes only 5 events of CKEditor in its event handling. In order to use other events, you need to use the CKEditor.editor object by accessing the editor property of the jQuery object.
So, you need to use something like this:
var myeditor = $('#test-editor').ckeditor({
customConfig: '../../assets/js/custom/ckeditor_config.js',
allowedContent: true
});
myeditor.editor.on('change', function(evt) {
console.log('change detected');
});

Javascript (Dojo): Is event-listener removed when object is destroyed

I create a dialog in which there are some buttons with events. When I destroy the dialog recursive programmatical or by pressing the X are there deleted all the created event-listener (hide, cancel, click1, click2)?
Because I call this part (here I posted only a simplified version of my code) very often (for different dialogs) and it seems that my code could have some memory leaks I want to eliminate them. So please tell me, is it necassary/make sense to remove the event-listener all by myself like eventHide.remove(); ?
Additional: I tried to use the on (like the eventHide) for the click- and cancel-events but it didn't work.
var myDialog = new Dialog({
content: 'Testdialog'
});
myDialog.show();
var btn1 = new dijit.form.Button({ label: "Ok" });
var btn2 = new dijit.form.Button({ label: "Help" });
myDialog.containerNode.appendChild(btn1.domNode);
myDialog.containerNode.appendChild(btn2.domNode);
var eventHide = on.once(myDialog, "hide", function(e){
console.log('hide');
myDialog.destroyRecursive();
});
dojo.connect(btn1, "onClick", function(){
console.log('click ok');
myDialog.destroyRecursive();
});
dojo.connect(btn2, "onClick", function(){
console.log('click help');
myDialog.destroyRecursive();
});
dojo.connect(myDialog, "onCancel", function(){
console.log('cancel');
});
You could use this.own defined in dijit/Destroyable, which is a base of dijit/_WidgetBase and thus most widgets (make sure your custom widget inherit from hit.).
dijit/Destroyable is used to track handles of an instance, and then destroy them when the instance is destroyed.
More infos:
http://dojotoolkit.org/reference-guide/1.10/dijit/Destroyable.html
http://dojotoolkit.org/reference-guide/1.8/dojo/Evented.html

Backbone.js. Make change event correctly

I'm writing Todo app with Backbone.js
You can see part of my code below.
Model:
var Todo = Backbone.Model.extend({
defaults : {
title: 'Task Title',
complete: false
},
initialize: function(){
this.on("change:complete", function () {
alert("foo");
});
}
});
View:
var AppView = Backbone.View.extend({
collection: todoCollection,
el: 'body',
events: {
'click #tasks li .complete-task' : 'toggleComplete'
}
toggleComplete: function (e) {
var modelCid = $(e.target).parent('li').attr('id');
if ( this.collection.get(modelCid)['complete'] ){
this.collection.get(modelCid)['complete'] = false;
} else {
this.collection.get(modelCid)['complete'] = true;
};
}
});
But something working wrong and change event in the model doesn't working. I can't understand where I have mistakes.
Help me, please.
10q.
As per the Backbone Documentation:
Set model.set(attributes, [options])
Set a hash of attributes (one or
many) on the model. If any of the attributes change the model's state,
a "change" event will be triggered on the model. Change events for
specific attributes are also triggered, and you can bind to those as
well, for example: change:title, and change:content. You may also pass
individual keys and values.
So you need to be using the set method on the model for these events to be fired. So you would need to use something like this:
this.collection.get(modelCid).set('complete',false);

How to wait for a function to complete before executing another function

I'm using selecter jquery. I initialize it by typing the code
$("select").selecter();
I need to make sure that the formstone selecter jquery library has completed before i start appending elements. So what i did is to is use the $.when function
initialize: function(){
$.when($("select").selecter()).then(this.initOptions());
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
But this does not work. How can i wait while formstone selecter is doing its thing before i execute another function?
Thanks,
UPDATE
Here's the update of what i did but it does not work.
initialize: function(){
$("select").selecter({callback: this.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
There is a callback option.
The function passed as a callback will receive the newly selected value as the first parameter
Should be $("select").selecter(callback: function() { alert('callback fired.') });
or as shown
$("select").selecter({
callback: selectCallback
});
function selectCallback(value, index) {
alert("VALUE: " + value + ", INDEX: " + index);
}
The problem which I think regarding the callback edited code is that this can refer to anything. Try the following code
var selectorObj = {
initialize: function(){
$("select").selecter({callback: selectorObj.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
};
Created a working fiddler for you http://jsfiddle.net/6Bj6j/
The css is out of shape. Just select what is poping up when you click on the dropdown. You will get an alert which is written in the callback.
The problem with the provided snippet is the scope of the callback:
var selectorObj = {
initialize: function(){
$("select").selecter({ callback: selectorObj.initOptions });
},
initOptions: function(){
// 'this' refers to the "$('.selecter')" jQuery element
this.addClass('something');
}
};
However if you just need to add a class to the rendered element, you should use the 'customClass' option:
$("select").selecter({
customClass: "something"
});
If you need to do more, you can always access the Selecter element directly:
var $selecter = $("select").selecter().next(".selecter");
$selecter.addClass("something").find(".selecter-selected").trigger("click");
Sidenote: I'm the main developer of Formstone. If you have any suggestions for new features or better implementation, just open a new issue on GitHub.

Backbone.js views - binding event to element outside of "el"

The 2nd answer to this question nicely explains how event declarations in Backbone.js views are scoped to the view's el element.
It seems like a reasonable use case to want to bind an event to an element outside the scope of el, e.g. a button on a different part of the page.
What is the best way of achieving this?
there is not really a reason you would want to bind to an element outside the view,
there are other methods for that.
that element is most likely in it's own view, (if not, think about giving it a view!)
since it is in it's own view, why don't you just do the binding there, and in the callback Function,
use .trigger(); to trigger an event.
subscribe to that event in your current view, and fire the right code when the event is triggered.
take a look at this example in JSFiddle, http://jsfiddle.net/xsvUJ/2/
this is the code used:
var app = {views: {}};
app.user = Backbone.Model.extend({
defaults: { name: 'Sander' },
promptName: function(){
var newname = prompt("Please may i have your name?:");
this.set({name: newname});
}
});
app.views.user = Backbone.View.extend({
el: '#user',
initialize: function(){
_.bindAll(this, "render", "myEventCatcher", "updateName");
this.model.bind("myEvent", this.myEventCatcher);
this.model.bind("change:name", this.updateName);
this.el = $(this.el);
},
render: function () {
$('h1',this.el).html('Welcome,<span class="name"> </span>');
return this;
},
updateName: function() {
var newname = this.model.get('name');
console.log(this.el, newname);
$('span.name', this.el).text(newname);
},
myEventCatcher: function(e) {
// event is caught, now do something... lets ask the user for it's name and add it in the view...
var color = this.el.hasClass('eventHappened') ? 'black' : 'red';
alert('directly subscribed to a custom event ... changing background color to ' + color);
this.el.toggleClass('eventHappened');
}
});
app.views.sidebar = Backbone.View.extend({
el: '#sidebar',
events: {
"click #fireEvent" : "myClickHandler"
},
initialize: function(){
_.bindAll(this, "myClickHandler");
},
myClickHandler: function(e) {
window.user.trigger("myEvent");
window.user.promptName();
}
});
$(function(){
window.user = new app.user({name: "sander houttekier"});
var userView = new app.views.user({model: window.user}).render();
var sidebarView = new app.views.sidebar({});
});
Update: This answer is no longer valid/right. Please see other answers below!
Why do you want to do this?
Apart from that, you could always just bind it using regular jQuery handlers. E.g.
$("#outside-element").click(this.myViewFunction);
IIRC, Backbone.js just uses the regular jQuery handlers, so you're essentially doing the same thing, but breaking the scope :)

Categories

Resources