How to get value of the last changed option on a combobox - javascript

Pure jQuery version:
$('select#register-type').live('change', function () {
console.log($(this).val());
});
Backbone view delegate event version:
App.Views.register = new (Backbone.View.extend({
tagName: 'section',
id: 'content',
template: _.template($('script.register').html()),
render: function () {
this.$el.html(this.template);
return this;
},
events: {
'change select#register-type': 'type'
},
type: function (event) {
// i want to console.log the current option selected...
}
}));
How can I achieve that? It seems i cant use $(this) like the jquery version, and this is referred to the register view object...

Use event.target
type: function (event) {
$(event.target).find('option:selected').val();
**OR**
$(event.target).val();
}

Related

RequireJS modules are undefined in Backbone view

I have been pretty much beginner at this part of javascript and I would appreciate any ideas how could be solved this problem.
I use requirejs to define my own modules where I also use backbone.js.
Let say I have the main module where I initialize my Backbone view which is rendered without any problem. Also, the click event where is calling method createSchemeForm creates the form correctly. The problem raises up in a situation when I call cancel method by click and the modules which are defined for Backbone view (e.g. "unicorn/sla/dom/helper"...) are undefined but when I called method createSchemeForm at the beginning the modules were executed without any problem.
Thank you in advance for any suggestions.
Backbone view
define("unicorn/sla/view/scheme", [
"unicorn/sla/dom/helper",
"unicorn/soy/utils",
"unicorn/sla/utils"
], function (DOMHelper, soyUtils, jsUtils) {
return Backbone.View.extend({
el: 'body',
inputData: {},
btnSaveScheme: 'btn-save-sla-scheme',
btnCancel: 'btn-cancel-sla-scheme',
btnCreate: 'btn-create-sla-scheme',
btnContainer: '#sla-scheme-buttons-container',
schemeContent: '#sla-scheme-content-section',
btnSpinner: '.button-spinner',
events: {
'click #btn-create-sla-scheme' : "createSchemeForm",
'click #btn-cancel-sla-scheme' : "cancel"
},
initialize: function(){
console.log("The scheme view is initialized...");
this.render();
},
createSchemeForm: function () {
this.spin();
DOMHelper.clearSchemeContent();
DOMHelper.clearButtonsContainer();
//Get button
$btnSave = soyUtils.getButton({isPrimary: 'true', id: this.btnSaveScheme, label: 'Save'});
$btnCancel = soyUtils.getButton({isPrimary: 'false', id: this.btnCancel, label: 'Cancel'});
//Append new created buttons
DOMHelper.addContent(this.btnContainer, AJS.format("{0}{1}", $btnSave, $btnCancel));
//Call service to get entry data for scheme creation form
AJS.$.ajax({
url: AJS.format('{0}={1}',AJS.I18n.getText('rest-url-project-scheme-input-data'), jsUtils.getProjectKey()) ,
type: "post",
async: false,
context: this,
global: false,
}).done(function (data) {
this.inputData = data;
$slaSchemeForm = soyUtils.getSchemeCreateForm({slaScheme : data, helpText: AJS.I18n.getText("sla-time-target-tooltip-text")});
DOMHelper.addContent(this.schemeContent, $slaSchemeForm);
jsUtils.scroll(this.schemeContent, 'slow');
}).fail(function () {
jsUtils.callFlag('error', AJS.I18n.getText("message-title-error"), AJS.I18n.getText("sla-error-load-scheme-input-data"));
}).always(function () {
this.stopSpin();
});
},
spin: function () {
AJS.$('.button-spinner').spin();
},
stopSpin: function () {
AJS.$('.button-spinner').spinStop();
},
cancel: function () {
jsUtils.clearButtonsContainer();
jsUtils.clearSchemeContent();
$btnCreateScheme = soyUtils.getButton({isPrimary: 'false', id: this.btnCreate, label: 'Create SLA Scheme'});
DOMHelper.addContent(this.btnContainer, $btnCreateScheme);
DOMHelper.addContent(this.schemeContent, soyUtils.getSchemesTable(new Array())); // TODO - get current data from server instead of empty array
}
});
});
Main module where is Backbone view initialize
define("unicorn/sla/project/batch", [
"unicorn/sla/utils",
"unicorn/sla/data/operations",
"unicorn/sla/data/validator",
"unicorn/sla/dom/helper",
"unicorn/sla/model/confirm/message",
"unicorn/sla/view/scheme",
"exports"
], function (jsUtils, operations, validator, DOMHelper, ConfirmMessage, SchemeView, exports) {
//Load project batch
exports.onReady = function () {
$schemeView = new SchemeView();
$schemeView.render();
}
});
AJS.$(function () {
AJS.$(document).ready(function () {
require("unicorn/sla/project/batch").onReady();
});
});

using OnClick function in Dojo

I cant seem to figure out how to use it - the following has no output
dom.create(
'a',
{
className: 'collapse',
onClick: function(){
console.log("something");
}
},
topPane.containerNode );
also tried
function testMe(){console.log('something')}
dom.create(
'a',
{
className: 'collapse',
onClick: testMe
},
topPane.containerNode );
Also this:
function testMe(){console.log('something')}
dom.create(
'a',
{
className: 'collapse',
onClick: testMe()
},
topPane.containerNode );
the last one causes testMe to be activated when the page is loaded (and not activated after click)
Try this:
var link = new domConstruct.create("a", {
href: "http://www.google.com",
innerHTML: "Google",
'class': "myClassHere",
onclick: "window.open(this.href); return false;",
onkeypress: "window.open(this.href); return false;"
});
or
var link = new domConstruct.create("a", {
href: "http://www.google.com",
innerHTML: "Google",
'class': "myClassHere",
onclick: function() { console.log("onclick"); },
onkeypress: function() { console.log("onkeypress"); }
});
I think that onClick is used when dealing with dojo/dijit/dojox widgets. But when setting events for html elements using the dojo/dom-construct, it is all lowercase (ie "onclick").
use dom-attr(domelement,"click",function(){})
it works
dom element is the one on which the click functionality is to be set.
in your example create a using dom construct and then use the above

Unable to bind click event in Backbone

I can't seem to bind a click event to an action in the snippet below. Any ideas?
var SelectView = Backbone.View.extend({
template: "#select-template",
initialize: function() {
this.render();
},
events: {
"click .placeholder": "optionsDropdown",
},
render: function() {
context = {className: this.className, options: this.model.get("options"), placeholder: this.model.get("placeholder")};
$(this.el).html(getHTML(this.template, context));
},
optionsDropdown: function() {
alert("Hello");
},
});
I think the problem is this line
className: this.className
I don't see the className variable anywhere in the view definition
var SelectView = Backbone.View.extend({
initialize: function () {
this.className = 'placeholder';
},
events: {
"click .placeholder": "optionsDropdown",
},
render: function () {
context = {
className: this.className,
options: this.model.get("options"),
placeholder: this.model.get("placeholder")
};
var template = _.template( $("#select-template").html(), context );
this.$el.html(template);
},
optionsDropdown: function () {
alert("Hello");
},
});
var Model = Backbone.Model.extend({});
var newModel = new Model({
'options' : 'Hello',
'placeholder' : 'Type your name'
});
var newView = new SelectView({model : newModel});
newView.render();
$('.container').append(newView.el);
Check Fiddle
You are binding the click event for the class="placeholder" which is supposed to be in the template. Once you define that it should work provided that you have the element with that class in your template.
Calling render from initialize
You're missing a selector in the event definition. It should be something like this (assuming the input id is optionsId):
events : {
"click #optionsId": "optionsDropDown"
}
you can have a DOM element binded to the handler e.g., "click li":"optionsDropDown"
edit: you are missing the target element.. heres a working fiddle
http://jsfiddle.net/FGeJd/

Trigger function on click if View has a certain class (backbone.js)

I have a div generated by a backbone.js view. When the user clicks on this div, a class active is added to the div and the function addToSet is executed.
Problem: I want another function to be triggered when the View's div has the class active. However, my attempt shown below always cause addToSet function to run when its clicked.
Now, I remove 'click': 'addToSet' from the events function, leaving only 'click .active': 'removeFromSet'. Clicking on the div does not cause anything to happen! Is this because the event handler cannot select the div of the view itself, just the elements inside it?
Any idea how I can solve this problem? Thanks!
JS Code
SetView = Backbone.View.extend({
tagName: 'div',
className: 'modal_addit_set',
template: _.template( $('#tpl_modal_addit_set').html() ),
events: {
'click': 'addToSet',
'click .active': 'removeFromSet'
},
initialize: function(opts) {
this.post_id = opts.post_id;
},
render: function() {
$(this.el).html( this.template( this.model.toJSON() ) );
if(this.model.get('already_added'))
$(this.el).addClass('active');
return this;
},
addToSet: function() {
$.post('api/add_to_set', {
post_id: this.post_id,
set_id: this.model.get('id'),
user_id: $('#user_id').val()
});
},
removeFromSet: function() {
$.post('api/remove_from_set', {
post_id: this.post_id,
set_id: this.model.get('id')
});
}
});
Have you tried to use a :not(.active) selector for one of your event delegates? This may help differentiate between the two scenarios.
Something like this:
events: {
'click :not(.active)' : callback1
'click .active' : callback2
}
These events:
events: {
'click': 'addToSet',
'click .active': 'removeFromSet'
}
don't work and you sort of know why. From the fine manual:
Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el).
So your 'click': 'addToSet' binds addToSet to a click on the view's el itself but 'click .active': 'removeFromSet' binds removeFromSet to a .active element inside the view's el.
I think the easiest solution is to have a single event:
events: {
'click': 'toggleInSet'
}
and then:
toggleInSet: function() {
if(this.$el.hasClass('active')) {
$.post('api/remove_from_set', {
post_id: this.post_id,
set_id: this.model.get('id')
});
}
else {
$.post('api/add_to_set', {
post_id: this.post_id,
set_id: this.model.get('id'),
user_id: $('#user_id').val()
});
}
}
You could use an instance variable instead of a CSS class to control the branching in toggleInSet if that makes more sense.

Calling functions with click handlers in ExtJS 4

I have a function inside a toolbar, let's call it:
Ext.define('MyArchive.Toolbar', {
search: function() {
console.log('searching');
}
}
Now I'd like to call this function when clicking a button. So I'm adding some click handlers in the afterRender on the toolbar setup:
afterRender: function() {
Ext.getCmp('search-button').on('click', this.search);
}
However, this doesn't work and I ultimately need to go the full route of:
afterRender: function() {
Ext.getCmp('search-button').on('click', function() {
quick_search();
)};
}
Any particular reason why my first attempt doesn't apply the click handler as I expect?
Thanks for any explanations or refactorings! Additional patterns/idioms welcome...
Next try:
var panelOverall = new Ext.form.FormPanel({
html: 'bla',
search: function() {
console.log('searching');
},
buttons: [
{
text: 'Moo',
id: 'button1',
handler: function(){
//window.destroy();
}
}
],
afterRender: function() {
Ext.getCmp('button1').on('click', this.search);
}
});
is working for me.. am I missing something?

Categories