我開始學習backbone.js,並且我已經構建了我的第一個頁面,並且我想知道如果我沿着「正確」路徑行進(如就像軟件中有一條正確的道路一樣)。我正在使用模型&視圖在backbone.js中正確
是否可以讓模型屬性(屬性)自動綁定到html元素?
的HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>settings page</title>
<link rel="stylesheet" type="text/css" href="../Content/theme.css" />
<script language="javascript" src="../Scripts/jquery-1.7.1.js"></script>
<script language="javascript" src="../Scripts/underscore.js"></script>
<script language="javascript" src="../Scripts/backbone.js"></script>
<script language="javascript" src="../Scripts/settings.js"></script>
</head>
<body>
<div style="width:95%;margin:10px;padding:10px;background-color:#ffffff;color:#000000;padding-bottom:8px;padding-right:5px;padding-top:4px;float:left;">
<h1>
Settings...
</h1>
Server URL (cloud based API):
<br />
<input id="settings-service-url" type="text" size="100" />
<br />
<br />
Timeout:
<br />
<input id="settings-timeout" type="text" size="100" />
<br />
<br />
<button id="update-settings">Update Settings</button>
</div>
</body>
</html>
的Javascript:
$(document).ready(function() {
if (typeof console == "undefined") {
window.console = { log: function() { } };
}
Settings = Backbone.Model.extend({
defaults: {
ServiceUrl: "",
Timeout: 0
},
url: function() {
return '/settings';
},
replaceServiceUrlAttr: function (url) {
this.set({ WisdomServiceUrl: url });
},
replaceTimeoutAttr: function (timeout) {
this.set({ Timeout: timeout });
}
});
SettingsView = Backbone.View.extend({
tagName: 'li',
events: {
'click #update-settings': 'updateSettings'
},
initialize: function() {
_.bindAll(this, 'render');
this.settings = new Settings;
this.settings.fetch({ success: function() {
view.render(view.settings);
}
});
},
updateSettings: function() {
view.settings.replaceServiceUrlAttr($('#settings-service-url').val());
view.settings.replaceTimeoutAttr($('#settings-timeout').val());
view.settings.save();
},
render: function (model) {
$('#settings-wisdom-service-url').val(model.get("WisdomServiceUrl"));
$('#settings-timeout').val(model.get("Timeout"));
}
});
var view = new SettingsView({ el: 'body' });
});