2012-05-16 177 views
0

有一個頁面顯示對象列表(例如書籍)。 此列表可以通過客戶端交互以編程方式增加。 哪種方法可以在DOM中創建新的「書籍」?客戶端模板,服務器端模板或原始克隆和編輯存根DOM元素客戶端?

我想在DOM中創建一個不可見的對象存根,然後將其克隆n次,每次編輯屬性(例如書的標題和拇指)。

哪個是最佳做法?

性能不是主要關注點。代碼的可管理性和簡單性是我的焦點。 我已經使用jQuery。

+0

數據綁定框架還有的項目,這個基本的CRUD的東西噸。最容易爲你和用戶?顯示一個表格,允許用戶添加一行。以前在jQuery中已經做過無數次了。 – Konerak

+0

@Konerak我環顧四周,但我還沒有找到一個明確的最佳實踐,所以我在這裏問了解哪個是處理這個問題的常用方法,哪些是最新的解決方案。對不起,如果看起來微不足道。 – micred

回答

2

避免「克隆」並使用客戶端模板解決方案,如MustacheHandlebars。加載你的模板(變量預裝,通過AJAX,等等),它們緩存(在對象,數組變量,等等)進行再利用,然後通過jQuery構建它們:

//the data 
var data = { 
    text : 'foo' 
} 

//HTML template string 
var templateString = '<div><span>{{text}}</span></div>'; 

//render contents to template 
var templateWithData = Mustache.render(templateString,data); 

//build using jQuery 
//should now be a div that has a span that contains foo 
var newElement = $(templateWithData); 
0

您可能需要使用模板引擎。我個人最喜歡的是icanhaz.js,但還有很多其他解決方案可用。

0

你最好用數據綁定框架/引擎代替模板引擎。

knockoutjs

//View (Template) 
<form data-bind="submit: addItem"> 
New item: 
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' /> 
    <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button> 
    <p>Your items:</p> 
    <select multiple="multiple" width="50" data-bind="options: items"> </select> 
</form> 

// ViewModel - Here's my data model 
var SimpleListModel = function(items) { 
    this.items = ko.observableArray(items); 
    this.itemToAdd = ko.observable(""); 
    this.addItem = function() { 
     if (this.itemToAdd() != "") { 
      this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update. 
      this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable 
     } 
    }.bind(this); // Ensure that "this" is always this view model 
}; 

ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"])); 

Try it in jsFiddle