2013-01-08 21 views
9

我正在與Backbone.js第一次,並試圖讓我的頭瞭解它是如何工作的。我有一個搜索表單,通過Ajax提取結果並動態地將它們寫入頁面。搜索表單和結果的主幹結構?

我現在試圖弄清楚如何在Backbone - I read this SO question中構建這個結構,但我不完全理解如何將表單和結果連接在一起。

這裏是我的HTML:

<form id="flight-options"> <!-- options for user to choose--> 
<input type="radio" name="journey" value="single">Single<br/><input type="radio" name="journey" value="return">Return 
<input type="checkbox" name="airline" value="aa">AA<br><input type="checkbox" name="airline" value="united">United 
</form> 
<div id="results"> <!-- results, written by Ajax --> 
<h3>Results</h3> 
<ul id="results-list"> 
</div> 

以下是我正在考慮構建骨幹代碼:

var SearchModel = Backbone.Model.extend({ 
    performSearch: function(str) { 
     // fire the ajax request. provide a bound 
     // _searchComplete as the callback 
    }, 
    _searchComplete: function(results) { 
     this.set("searchResults", results); 
    } 
    }); 
    var SearchFormView = Backbone.View.extend({ 
    tagName: "form", 
    id: "flight-options", 
    events: { 
     "click input": "getResults" 
    }, 
    getResults: function() { 
     // Get values of selected options, use them to construct Ajax query. 
     // Also toggle 'selected' CSS classes on selected inputs here? 
     this.model.performSearch(options); 
    } 
    }); 
    var SearchResultsView = Backbone.View.extend({ 
    tagName: "ul", 
    id: "results-list", 
    initialize: function() { 
     this.model.on("change:searchResults", this.displayResults, this); 
    }, 
    displayResults: function(model, results) { 
     //append results to results-list here. 
     //update contents of blurb here? 
    } 
    }); 
    var searchModel = new SearchModel(); 
    var searchFormView = new SearchFormView({ model: searchModel }); 
    var searchResultsView = new SearchResultsView({ model: searchModel }); 

我的問題:

  1. 這基本上是一個合理的結構使用,一個視圖用於表單,一個用於結果 - 更新模型的第一個視圖,觀看模型的第二個視圖?
  2. 我還想更新<h3>結果標題的內容,當有新結果時 - 在上面的代碼中,哪裏是最明智的做法?
  3. 我想要在用戶點擊表單輸入時在輸入上切換selected類 - 在上面的代碼中,哪裏是合乎邏輯的位置?

感謝您的幫助。

回答

5
  1. 是的,這是一個邏輯組織和使用Backbone Views的好方法。
  2. 你可以處理這個幾個方面:
    • 有標題(例如SearchResultsTitleView)也監聽在模型更改一個單獨的視圖。這對我來說似乎有點過分。
    • 讓您的SearchResultsView更新標題<h3>和結果<ul>。它可能與綁定到#results-list<ul>,而不是綁定到#results<div>並具有兩個功能,一個用於更新每個孩子。
  3. 這似乎是SearchFormView的責任,既可以監聽模型的更改,也可以更新事件發生時的狀態。
+1

非常感謝 - 對不起,這不是最令人興奮的問題,但只需要一些指導! – Richard

+0

當然,沒問題。 –