我想了解Backbone.js以及它是如何工作的。我已经创建了两个带有任何值的文本框,并且单击按钮(Multipy),这些值显示在下面的框中,这可以工作,但我希望在第三个框中显示两个值的乘法 - 我试图分配两个值变量和乘法但它似乎不起作用。我认为文本框的返回值存在一些问题,认为它是NAN。无论如何,请看看并提出建议。我已经注释掉了无效的代码。 实时网址:http://egoless.co.uk/learning/learn_backbone/first-backbone-app.php
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore.js">
</script><script type="text/javascript" src="backbone.js"></script>
<style>
.size {
width: 100px;
height: 30px;
border: solid 1px red;
float: left;
margin-left: 10px;
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<input type="text" id="box1" />
<input type="text" id="box2" />
<button id="myBtn">Multiply</button>
<br>
<br>
<div id="myBox" class="size"></div>
<div id="myBox2" class="size"></div>
<div id="myBox3" class="size"></div>
<script>
(function($){
//defining model 1
PersonModel1 = Backbone.Model.extend({
defaults:{
age : function(){
return $("input#box1").val();
}
}
});
myPerson1 = new PersonModel1();
//defining model 2
PersonModel2 = Backbone.Model.extend({
defaults:{
age : function(){
return $("input#box2").val();
}
}
});
myPerson2 = new PersonModel2();
//defining collection
Group = Backbone.Collection.extend({
Model: PersonModel1,
Model: PersonModel2,
url:"#"
})
People = new Group([]);
People.add(myPerson1);
People.add(myPerson2);
//adding view
ResultView = Backbone.View.extend({
el:'button',
events:{
'click':'render'
},
render:function(){
val1 = myPerson1.get('age');
val2 = myPerson2.get('age')
val3 = val1*val2 // not working
$('div#myBox').html(val1);
$('div#myBox2').html(val2);
$('div#myBox3').html(val3); // not working
$('input#box1').val("");
$('input#box2').val("");
return this;
}
})
$(document).ready(function(e) {
myResultView = new ResultView();
});
})(jQuery);
</script>
</body>
</html>
答案 0 :(得分:0)
在模型定义的默认值部分中,您只能为属性赋值。 要返回值年龄,你应该写单独的函数。
defaults:{},
age : function(){
return $("input#box1").val();
}
你可以像这样打电话
val1 = myPerson1.age();
val2 = myPerson2.age();
val3 = val1*val2 ;