前陣子第一次聽到這個程式的名稱,大概是說 可以寫成 Javascript 的 MVC 的程式
官方網站裡面有些範例,看了可以稍微了解一點
Why would you use Backbone.js?
What is a model?
What is a view?
What is a router?
What is a collection?
一般最常用到的是 Model ,非常好用,除非要建構整個網站,不然應該還不用用到 router 跟 view
研究了一下寫了一個 階層的程式
這是主要結構:
window.SelectOptLoading = Backbone.View.extend({
initialize: function () {
this.el.find(':first').prop('selected', true);
this.post = new CategoryModel();
},
events: {
"change .form-dropdown": "selOption",
},
selOption: function (e) {
if (!_.isEmpty(e.target.value)) {
this.loadOption(e.target.value);
}
},
setOption: function (value, time) {
var _this = this;
if (time && this.el.find('.form-dropdown option').size() == 0) {
_.delay(function () {
_this.setOption(value, time);
}, 300);
} else {
this.el.find('.form-dropdown').val(value);
}
},
loadBefore: function () {},
loadOption: function (data, time) {
if (typeof data == 'object') {
this.post.set(data);
} else {
this.post.set({
'parent': data
});
data = this.post.attributes;
}
this.setOption(data.parent, time);
this.loadBefore();
var _this = this;
$.post('ajax.php', _this.post.attributes, function (rt) {
if (rt.ok) {
var template = _.template($("#option_item").html()),
items = rt.items,
ret = template({
value: '',
label: 'Select'
});
ret += _.map(items, function (obj) {
return template({
value: obj.identity,
label: obj.label
})
});
if (typeof _this.el.attr('for') == 'string') {
$('#' + _this.el.attr('for')).html(ret);
}
_this.loadAfter(items);
} else {
_this.loadError(rt);
}
}, 'json')
},
loadAfter: function (items) {},
loadError: function (rt) {}
}); 稍微解釋一下 this.post = new CategoryModel();
這是我用來傳送POST的Model
可以在 loadBefore 先把 POST 的值給改變
$(“#option_item”).html() 的值是
<script type="text/template" id="option_item"><option value="<%=value%>"><%=label%></option></script> <span id="form_category_area" class="select_area" for="form_books"> <select id="form_category" class="form-dropdown"><option value="" selected="selected">Select</option></select> </span>
兩個控件 一個 跑 第一階 form_category,然後外層必須包一層,然後指定改變目標的值 for=”form_books”
另外 backbone 還有配合這個 underscore 非常好用的程式
http://documentcloud.github.com/underscore/
做個紀錄,寫的還不是很好~