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)
.
相关小提琴(不是我的提琴,但可以使用) http://jsfiddle.net/thomas/C9wew/4/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.