backbone.js - change or click events not firing - javascript

I am getting started with backbone.js but it seems i am not able to get the first hand code correct. I looked up all the resources but cant figure out what is the problem.
I was expecting changed event getting fired every time i change something in the input box and finally when i click the button, it should fire someAction function. There are no JavaScript errors but nothing happens. no change or click event getting fired.
Can someone please tell me what am i missing here?
Aspx Page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
<script src="underscore.js" type="text/javascript"></script>
<script src="Backbone.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
Person = Backbone.Model.extend({
el: '#form1',
events : {
"click #DoSomething": "someAction"
},
initialize: function(){
//This will bind change event of input controls to below function
_.bindAll(this, "changed");
},
//This function will be fired whenever value in the input is changed
changed: function(evt) {
var target = $(evt.currentTarget),
data = {};
data[target.attr('name')] = target.attr('value');
this.model.set(data);
alert('Model Updated')
},
//take some action on click of a button
someAction: function(){
var fName = this.model.get('FirstName');
var lName = this.model.get('LastName');
alert("First Name" + fName + " Last Name " + lName);
return false;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>First Name</span>
<input type="text" name="FirstName" id="txtFirstName" value="Mark" />
<span>Last Name</span><input type="text" name="LastName" id="txtLastName" value="Waugh" />
<input type="button" id="DoSomething" value="Login Here" />
</div>
</form>
</body>
</html>

All of your functionality should be in a view not a model.
Change Person = Backbone.Model.extend to PersonView = Backbone.View.extend. Now you actually have to create an instance of the view.
$(function() {
PersonView = Backbone.View.extend({
...
});
window.personview = new PersonView();
});

_.bindAll(this, "changed"); won't bind to the changed event. You need to add 'change input': 'changed' to your events list. The bindAll isn't needed at all.
Also, I believe this.model is undefined. I think you should be using this.set(data) instead of this.model.set(data).

Relevant fiddle (this is not mine but it works)
http://jsfiddle.net/thomas/C9wew/4/

Related

Show alert error message when certain condition arises

I have the following code on page load that I use to show an error alert:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["message"] == "noemployees")
AlertDanger.Visible = true;
This is where the error is called. The page reloads and the error is shown.
if (payFitments == null)
{
Response.Redirect("Default?message=noemployees");
}
I have the following markup
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function () {
$(".alert").fadeTo(1500, 0).slideUp(500, function () {
$(this).remove();
});
}, 3000);
});
-------------------------
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
×
<strong>You must have at least one employee to process</strong>
</div>
How do I show this message without having to load the default page again? Not seeing examples on the web that show this clearly.
You're using JQuery remove, which effectively deletes the alert from your DOM. So showing it again without reloading your page is not possible.
But you could use JQuery detach instead. Then you can insert it again with appendTo.
var alert = null;
function showHideAlert() {
if (alert) {
alert.appendTo("body");
alert = null;
} else {
alert = $(".alert").detach();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<button onclick="showHideAlert();">Show/Hide alert</button>
<div class="alert">ALERT!!!</div>
</body>
Try serving a static html file and then using the alert function in Javascript. You can learn that here. Example for a button press:
<html>
<head>
<script>
function onError() {
try {
...
} catch (...) {
var error
error = "button was pressed"
alert(error)
}
}
</script>
</head>
<body>
<button id="myButton" onClick="onError()">do not click</button>
</body>
</html>
<html>
<head runat="server">
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" /><%-- Also Check Compatible View --%>
<%-- Put all your jQuery... Here I'm showing an example--%>
<script src="//ajax.microsoft.com/ajax/jQuery/jquery-2.1.1.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
window.setTimeout(function() {
$(".alert").fadeTo(1500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
});
</script>
<form id="form1" runat="server">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
× <strong>You must have at
least one employee to process</strong>
</div>
</form>
</body>
</html>
Note:- I think you have missed this... put your jQuery code inside your body tag...

Get Current Logged Username in my app

I would like to get the current logged in username and display it my frontend.
Currently I have a function called GetCurrentUser() that gets called when a button is clicked.
<button type="submit" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; "value="Submit">Save Selections</button><br>
function GetCurrentUser() {
var usrName ="#HttpContext.Current.User.Identity.Name.ToString()";
//var usrName = '<%HttpContext.Current.User.Identity.Name %>';
//document.getElementById("UserName").innerHTML = usrName;
console.log(usrName);}
I get the follwoingoutput in my console log--> #HttpContext.Current.User.Identity.Name
If you are seeing the literal output of "HttpContext.Current.User.Identity.Name " then your JS function is generated client side after you have lost server context.
Couple options for you:
Call back to your controller via ajax to get the username
Store the username in a read only field on page load (kinda like setting a form value) and retrieve the value via jquery or js on function call
Assign the username on page load to a global js element and just use that element in your function.
Here is an example of 2 and 3. I don't think you should worry about #1 until you fully understand why your issue is happening in the first place:
<div class="btn btn-info" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; " value="Submit">Save Selections</div><br>
<input type="hidden" name="method2" id="method2" value="#System.Security.Principal.WindowsIdentity.GetCurrent().Name">
#section scripts {
<script>
var globalSettingMethod = '#System.Security.Principal.WindowsIdentity.GetCurrent().Name';
function GetCurrentUser() {
alert(globalSettingMethod);
alert($('#method2').val());
}
</script>
}
I could get the user logged in by passing the script at the end of the document.
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Example.SiteMaster" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form runat="server">
</form>
<script>
var loggedUser = "<%: HttpContext.Current.User.Identity.Name %>";
</script>
</body>
</html>
I hope you find it useful.

There's a box supposed to pop up after clicking the "Click Me" button

I was working on variables and loop frames and stumbled across this problem. I tried switching some things around but none have succeeded. I put the code in a validator and it showed the document as valid.
Whats missing?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value
if (myValue.length == 0) {
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<input type="submit" value="Click Me" onclick="substitute" />
</body>
</html>
Mentioning the name of a variable holding a function doesn't call the function. You have to actually call it explicitly.
This is usually done by placing () after the reference to the function.
onclick="substitute()"

Detect change of value of struts2 autocompleter tag using javascript or jquery

I am working on Struts 2 application. In my application, I need to use Struts 2 autocompleter tag. For that I have used struts2-dojo-plugin-2.3.1.2.jar jar file. I need to fetch the value from autocompleter once the value changes. I tried using onchange event but it was not working. Here is my code:
<%#taglib uri="/struts-dojo-tags" prefix="sx"%>
<html>
<head>
<script type="text/javascript">
function abc() {
var a = dojo.widget.byId("country");
var value1 = a.getSelectedValue();
document.getElementById("myText").value = value1;
}
</script>
<sx:head />
</head>
<body>
<sx:autocompleter name="country"
id="country" onchange="abc();" list="cricketNations" />
</body>
</html>
How do I achieve this. Help me solve this issue.
The struts2-dojo-plugin is deprecated. You need to use struts2-jquery-plugin.
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head jqueryui="true"/>
</head>
<body>
<div id="myText" class="result ui-widget-content ui-corner-all"></div>
<sj:autocompleter name = "country"
id = "country"
onChangeTopics = "autocompleteChange"
list = "%{cricketNations}" />
<script>
$.subscribe('autocompleteChange', function(event, data) {
var ui = event.originalEvent.ui;
var message = ui.item.value;
if (ui.item.key) {
message = '( '+ ui.item.key +' ) '+message;
}
$('#myText').html('<b>'+message+'</b>');
});
</script>
</body>
</html>
You might not be able to use HTML attributes with dojo widgets, you need to use dojo topics to subscribe for an event:
<%#taglib uri="/struts-dojo-tags" prefix="sx"%>
<html>
<head>
<script type="text/javascript">
dojo.event.topic.subscribe("/countryName", function(value, key, text, widget){
alert('inside onchange');
document.getElementById("myText").value = value;
});
</script>
<sx:head />
</head>
<body>
<sx:autocompleter name="country" valueNotifyTopics="/countryName" list="cricketNations" />
</body>
</html>
When value is selected for sx:autocompleter, topics will be published. See autocompleter doc here.

Ajax `appendTo` replaces the existing element

I am trying to submit some form data to Servlet using JQuery and retrieve the Servlet response from the same JQuery. Please have a look at the below code.
<%--
Document : index
Created on : Feb 23, 2015, 8:18:52 PM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var form = $('#customItemForm');
function formSubmit(){
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data);
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
</script>
</head>
<body>
<form method="get" action="SampleServlet" id="customItemForm" onsubmit="formSubmit(); return false;">
Name <input type="text" name="name">
<button>Submit</button>
</form>
<br>
<div id="results"></div>
</body>
</html>
In the above code in JQuery section, I am trying to read the value I got from servlet, create a Text Input in a DIV. My expectation was if I click the "Submit" button twice, then 2 text boxes; if I click the submit button thrice, then 3 text boxes and so on. Unfortunatly it is not happening here. Only one text box appear, all the time, replacing the previous one.
How can I fix this?
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data); //replace with $("#results").append(data)
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
you need to make the change above as .text() replaces the existing data in the div (so the previous run you did gets over-written)

Categories