[英]Issues with backbone.js binding
我是骨干新手,試圖通過綁定來獲取模型更新以更新我的html,但沒有運氣。 我正在使用jquery.window插件創建彈出窗口。 檢查我按更改標題按鈕並更新我的模型標題,html不會更新。 非常感謝您的幫助,謝謝
埃里克
這是我的代碼
HTML:
<!DOCTYPE html>
<html>
<head>
<title>I have a back bone</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script src="js/jquery.window.js"></script>
<script src="js/underscore.js"></script>
<script src="js/backbone.js"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/jquery.window.css">
<button id="add-window">Add Window</button>
<button id="change-title">Change Title</button>
<script type="text/template" id="search_template">
<label><%= title %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
</body>
</html>
Javascript:
(function($) {
AppWindow = Backbone.Model.extend({
title : "John",
window : null
});
AppWindows = Backbone.Collection.extend({
initialize : function(models, options) {
this.bind("add", options.view.addWindowView);
}
});
WindowView = Backbone.View.extend({
initialize : function(){
_.bindAll(this, "render");
this.model.bind("change:title");
this.template = _.template($("#search_template").html());
this.render().el;
},
render : function(){
var formString = this.template(this.model.toJSON());
var win = $.window({
icon : 'http://www.fstoke.me/favicon.ico',
title : this.model.get("title"),
content : formString,
x : 80,
y : 80,
resizable : true,
});
this.el = $("#" + win.getWindowId()+".window_frame");
this.delegateEvents(this.events);
return this;
}
});
AppView = Backbone.View.extend({
views: {},
el : $("body"),
initialize : function() {
this.appWindows = new AppWindows(null, {
view : this
});
},
events : {
"click #add-window" : "addWindow",
"click #change-title" : "changeTitle"
},
addWindow : function() {
var window_title = "Eric";
var window_model = new AppWindow({
title : window_title
});
// Add a new model to our friend collection
this.appWindows.add(window_model);
},
changeTitle : function(){
var win = this.appWindows.at(0);
win.set("title", "jamjamajm");
},
addWindowView : function(model) {
var view = new WindowView({
model : model
});
model.set("window", view);
},
deleteWindow : function(wnd){
console.log("deleteing");
}
});
var appview = new AppView;
})(jQuery);
您忘記為WindowView
模型的change:title
綁定添加方法。
Backbone.js文檔對on
功能(也稱為綁定)說了以下內容:
object.on(event,callback,[context])別名:bind
將回調函數綁定到對象。 每當觸發事件時,都會調用該回調。
因此,使用this.model.bind("change:title");
您剛剛提供了每次更改屬性title
都會觸發的事件。 您尚未提供回調函數,因此在觸發事件時沒有任何反應。 我假設您希望回調是WindowView
的render-function,因此應該可以解決此問題:
this.model.on("change:title", this.render); // changed to on as bind is deprecated but still supported
這樣,無論何時觸發事件change:title
,都將調用與模型相對應的WindowView
render
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.