客户端模板,服务器端模板或原始克隆和编辑存根DOM元素客户端?

问题描述:

有一个页面显示对象列表(例如书籍)。 此列表可以通过客户端交互以编程方式增加。 哪种方法可以在DOM中创建新的“书籍”?客户端模板,服务器端模板或原始克隆和编辑存根DOM元素客户端?

我想在DOM中创建一个不可见的对象存根,然后将其克隆n次,每次编辑属性(例如书的标题和拇指)。

哪个是最佳做法?

性能不是主要关注点。代码的可管理性和简单性是我的焦点。 我已经使用jQuery。

+0

数据绑定框架还有的项目,这个基本的CRUD的东西吨。最容易为你和用户?显示一个表格,允许用户添加一行。以前在jQuery中已经做过无数次了。 – Konerak

+0

@Konerak我环顾四周,但我还没有找到一个明确的最佳实践,所以我在这里问了解哪个是处理这个问题的常用方法,哪些是最新的解决方案。对不起,如果看起来微不足道。 – micred

避免“克隆”并使用客户端模板解决方案,如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); 

您可能需要使用模板引擎。我个人最喜欢的是icanhaz.js,但还有很多其他解决方案可用。

你最好用数据绑定框架/引擎代替模板引擎。

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